(function () {
    const
        transfer = require('transfer')
        , EventEmitter = require('myevents')
        , exec = require('child_process').exec
        , apiService = require('app-service')
        , nedbCollection = require('nedbCollection')
        , dbServer = require('db-server')
        , path = require('path')
        ;

    const icons = {
        error: nw.__dirname + '/web_content/assets/imgs/error.png',
        tick_folder: nw.__dirname + '/web_content/assets/imgs/tick_folder.png',
        upload_folder: nw.__dirname + '/web_content/assets/imgs/upload_folder.png',
        info: nw.__dirname + '/web_content/assets/imgs/info.png'
    };

    var downCount = 0,
        uploadCount = 0;
    transfer['window_load.complete'] = () => {
        let nedb = new nedbCollection('/loacl.db');
        let upload_queue, upload_time,
            down_queue, down_time;

        EventEmitter.on('down_notice', (file) => {

            let file_name = path.basename(file.path);
            let ext = path.extname(file_name).replace('.', '').toLowerCase();//取文件的后缀名，并且去掉‘.’号
            down_queue = {
                icon: "",
                body: file_name
            };

            dbServer.loacl.add({
                type: '1',
                path: file.path,
                name: file.name,
                size: file.size,
                cdate: Date.now(),
                ext: ext,
                url: file.url
            });

            EventEmitter.emit('task_complete_ctr');
            EventEmitter.emit('updataDownTaskNum', -1);

            downCount += 1;
            clearTimeout(down_time);

            // if (down_queue.length >= 10) { 
            //     sendNotice('下载完成', down_queue);
            // }
            // else

            down_time = setTimeout(() => {
                sendNotice('下载完成', down_queue, downCount);
                downCount = 0;
            }, 1000 * 3);
        });

        EventEmitter.on('upload_notice', (options) => {

            let file_info = options;
            let ext = options.extname && options.extname.replace('.', '').toLowerCase();
            upload_queue = {
                icon: "",
                body: file_info.name,
                tag: file_info._id
            };
            let new_file = {
                md5: file_info.md5,
                name: file_info.name,
                delflag: 0,
                pid: file_info.pid,
                cdate: Date.now(),
                ext: ext,
                size: file_info.size
            };
            apiService.add_item(new_file).then(function (e) {
                if (e.ret === 0 || !e.data) {
                    return;
                }
                EventEmitter.emit('fileListRefresh', e.data);
                EventEmitter.emit('getUserSpace', file_info.size);
            });
            dbServer.loacl.add({
                type: '2',
                path: file_info.path,
                name: file_info.name,
                size: file_info.size,
                cdate: Date.now(),
                ext: ext,
                url: ''
            });

            EventEmitter.emit('updataUploadTaskNum', -1);
            EventEmitter.emit('task_complete_ctr');
            uploadCount += 1;
            clearTimeout(upload_time);

            //if (upload_queue.length >= 10) sendNotice('上传完成', upload_queue);
            //  else 
            upload_time = setTimeout(() => { sendNotice("上传完成", upload_queue, uploadCount); uploadCount = 0; }, 1000 * 3);
        });

        EventEmitter.on('notice_msg', (title, error, icon) => {
            var notification = new Notification(title, {
                icon: icons[icon || 'info'],
                body: error,
                tag: 'error_msg'
            });
            notification.onclick = function () {
                this.close();
            };
            setTimeout(() => {
                notification.close();
            }, 5000);
        });

        function sendNotice(title, queue, len) {

            let temp = queue; // queue.splice(0, queue.length);
            if (!temp)
                return;

            notice(title, {
                icon: nw.__dirname + '/web_content/assets/imgs/notice.png',
                body: `${temp.body}` + (len == 1 ? title : `等${len}个文件${title}`),
                tag: temp.tag
            });
            // }
        }

        function notice(title, options) {
            var notification = new Notification(title, options);
            notification.onclick = function () {
                this.close();
            }
            setTimeout(() => {
                notification.close();
            }, 3000);
        }
    }
})();
