const Q = require('./q')
    , nedbCollection = require('nedbCollection')
    , dbServer = require('db-server')
    , taskStatus = require('taskStatus')
    , appCache = require('app-cache')
    , dirFile = require('dir-function')
    ;

class down {
    constructor() {
        this.nedb = new nedbCollection('down.d');
        this.nedbList = {};
    }
    nextTask() {
        return this.nedb.findOne({ 'status': taskStatus.wait}, { 'ctime':1,'fileid':-1 });
    }
    count() {
        return this.nedb.count();
    }
    remove(_id) {
        return this.nedb.delete({ '_id': _id });
    }
    modifyMd5(_id, url) {
        return this.nedb.update({ '_id': _id }, { 'url': url });
    }
    clear() {
        return this.nedb.delete({});
    }
    stop(selector) {
        if (typeof selector === 'string') {
            selector = { _id: selector };
        }
        return this.status(selector, taskStatus.stop);
    }
    status(selector, status) {
        if (typeof selector === 'string') {
            selector = { _id: selector };
        }
        return this.nedb.update(selector, { 'status': status });
    }
    find(selector) {
        return this.nedb.find(selector);
    }
    findAll(sort) {
        return this.nedb.find({},sort);
    }
    findOne(selector, sort) {
        return this.nedb.findOne(selector, sort);
    }
    add(datas) {
        if (!datas || (Array.isArray(datas) && !datas.length)){
            return Promise.resolve(false);
        }
            return this.find({ path: { $in: datas.map(v => v.path) } })
        .then(exits => {
            if (exits.length === 0) return datas;

            return  datas.filter(v => (exits.findIndex(d => d.path === v.path) === -1))
        }).then(d => {
            return d.length ? this.nedb.insert(d) : Promise.resolve(false);
        });
    }

    downRange(id, start_len) {
        return this.nedb.update({ '_id': id }, { 'start_len': start_len });
    }
}

module.exports = down;