const PATH = require('path')
    , assert = require('assert')
    , fs = require('fs')
    , dbServer = require('db-server')
    , uploadManager = require('uploadmanager')
    , apiService = require('app-service')
    , app_cache = require('app-cache')
    , event = require('myevents')
    , uploadTask = require('uploadtask')
    ;

var netErrorTime;
var IS_INIT = false;
function start() {
    uploadManager.startNext();
    dbServer.folder.nextTask().then(doc => {
        if (doc && doc.path) {
            IS_INIT = true;
            return readDir(doc);
        }
        dbServer.folder.count().then(e => {
            if (e !== 0) return start();
            event.emit('fileListRefresh');
            IS_INIT && event.emit('notice_msg', '文件夹', `文件夹已经全部读取完成！`, 'tick_folder');
        })
    });
}

function readDir(doc) {
    if (!doc.path || doc.path.indexOf('$RECYCLE.BIN') !== -1 || doc.path.indexOf('System Volume Information') !== -1) {
        return dbServer.folder.remove(doc._id).then(e => {
            return start();
        });
    }
    let files;
    try {
        files = fs.readdirSync(doc.path);
    } catch (e) {
        return dbServer.folder.remove(doc._id).then(e => {
            event.emit('notice_msg', '文件夹读取失败', `文件夹：${doc.path}读取失败！`, 'error');
            return start();
        })
    }

    dbServer.folder.remove(doc._id).then(e => {
        return apiService.add_item({
            name: PATH.basename(doc.path),
            pid: doc.pid,
            delflag: 0,
            isdir: 1
        })
    }).then(function (d) {
        if (d.ret === 0) {
            return dbServer.folder.add(doc.path, doc.pid).then(e => {
                if (d.net === -1) {
                    clearTimeout(netErrorTime);
                    event.emit('notice_msg', '网络错误', `网络错误，5秒自动重试.....`, 'error');
                    netErrorTime = setTimeout(() => {
                        start();
                    }, 5000);
                    return;
                }
                return start();
            })
        }
        if (files.length === 0) {
            return start();
        }
        saveDB(files, doc.path, d.data._id);
    });
}

function saveDB(data, filePath, pid) {
    let i = data.length;
    let files = [],
        folders = [];
    data.forEach((v,index) => {
        if (!v) {
            return;
        }
        v = PATH.resolve(filePath, v);
        let stat;
        try {
            stat = fs.statSync(v);
        } catch (e) {
            event.emit('notice_msg', '文件夹读取失败', `文件夹：${v}读取失败！`, 'error');
            return;
        }

        if (stat.isDirectory())
            folders.push(v);
        else
            files.push({
                name: PATH.basename(v),
                extname: PATH.extname(v),
                size: stat.size,
                mtime: stat.mtime,
                path: v,
                status: uploadTask.queue_status ? 0 : -2,
                end_len: 0,
                md5: '',
                url: '',
                pid: pid,
                sort:index
            });
    });

    if (!folders.length) {
        start();
    } else
        dbServer.folder.add(folders, pid).then(e => {
            start();
        });
    dbServer.upload.add(files).then((newDocs) => {
        if (newDocs) {
            event.emit('upload_taskList', newDocs);
            event.emit('updataUploadTaskNum', newDocs.length);
            event.emit('task_num_change');
        }
        uploadManager.startNext();
    });
}

module.exports = start;