(function () {
    const
        apiService = require('app-service')
        , downManager = require('downmanager')
        , path = require('path')
        , mkpath = require('mkpath')
        , request = require('request')
        , transfer = require('transfer')
        , dbServer = require('db-server')
        , taskStatus = require('taskstatus')
        , fs = require('fs')
        , event = require('myevents')
        ,appCache = require('app-cache')
        ;
    let cacheConfig = appCache.local_config();

    function getFiles(obj_id) {
        return apiService.item_list(obj_id).then(function (d) {
            return d;
        });
    }
    //  下载文件夹
    function downFolder(base_path, obj_id) {

        if (!fs.existsSync(base_path)) {
            mkpath.sync(base_path);
        }
        getFiles(obj_id).then(function (d) {
            let files = [];
            d.data.forEach((v) => {
                let folder_path = path.join(base_path, v.name);
                if (v.isdir) {
                    return downFolder(folder_path, v._id);
                }
                files.push({
                    "md5": v.md5,
                    "name": v.name,
                    "size": v.size,
                    "path": folder_path,
                    "status": 0,
                    "url": '',
                    'start_len': 0
                });
            });
            dbServer.down.add(files).then(e => {
                downManager.startNext();
            });
        });

    }
    //  下载文件
    function downFile(base_path, files) {
        if (files.length === 0) {
            return;
        }
        let tasks = [];
        files.forEach((v,index) => {
            let v_path = path.join(base_path, v.name);
            tasks.push({
                'fileid': v._id,
                'isdir': v.isdir,
                "md5": v.md5,
                "name": v.name,
                "size": v.size,
                "path": v_path,
                "status": taskStatus.wait,
                "url": '',
                'start_len': 0,
                'sort': index
            })
        });
        dbServer.down.add(tasks).then(newDocs => {
            if (newDocs && newDocs.length) {
                event.emit('down_taskList', newDocs);
                event.emit('updataDownTaskNum', newDocs.length);
                event.emit('task_num_change');
            }
            let num = cacheConfig.task.down_num;
            while (num > 0){
                num = num - 1;
                downManager.startNext();
            }
        });
    }

    transfer.downFileEntry = downFile;
}());