/**
 * Created by CSL on 2018-12-17.
 */

let mongoose = require('mongoose');
let blModel = mongoose.model('blockLibsModel');
let uuid = require('../../../public/web/uuid');

module.exports = {
    getLibNames: getLibNames,
    getLib: getLib,
    getLibNamesAndFirstLib: getLibNamesAndFirstLib,
    copyTemplateLib: copyTemplateLib,
    saveBlock: saveBlock
};

// userID、compilationID
async function getLibNames(data) {
    let libNames = await blModel.find({userID: data.userID, compilationID: data.compilationID}, ["libID","libName","-_id"]);
    return libNames;
};

// libID
async function getLib(data) {
    let lib = await blModel.findOne({libID: data.libID});
    return lib;
};

// userID、compilationID
async function getLibNamesAndFirstLib(data) {
    let libNames = await getLibNames(data);
    let lib = null;
    if (libNames.length == 0){
        lib = await copyTemplateLib(data.userID, data.userName, data.compilationID);
        libNames.push({libID: lib.libID, libName: lib.libName});
    }
    else{
        lib = await getLib(libNames[0]);
    }
    return {libNames: libNames, firstLib: lib};
};


async function copyTemplateLib(userID, userName, compilationID) {
    // let template = await getLib({libID: '00000000'});
    let template = {
        libID: "00000000",
        libName: "模板",
        datas: [
            {
                "ID": "00000001",
                "ParentID": "-1",
                "NextSiblingID": "00000002",
                "type": 1,
                "nodeName": "分类1"
            },
            {
                "ID": "00000002",
                "ParentID": "-1",
                "NextSiblingID": "00000003",
                "type": 1,
                "nodeName": "分类2"
            },
            {
                "ID": "00000003",
                "ParentID": "-1",
                "NextSiblingID": "-1",
                "type": 1,
                "nodeName": "分类3"
            }
        ],
        share: {
            "shareName": "共享",
            "shareTo": []
        }
    };

    let newLib = {
        userID: userID,
        compilationID: compilationID,
        libID: uuid.v1(),
        libName: `${userName}的块模板库`,
        datas: template.datas,
        share: template.share
    };
    newLib.share.shareName = `共享-${newLib.libName}`;
    await blModel.create(newLib);
    // console.log(JSON.stringify(newLib));
    return newLib;
};

/*------------------------------------------------------------------------------
参数：   {libID: n, nodeID: m, create: {node} | delete: true | update: {A:'xxx', B:'xxx'} }
说明：   libID、nodeID 必须。 create|update|delete三选一。
        create属性值：完整的node节点数据。
        delete属性值：固定为true(false没有实际意义)。
        update属性值：列出多个要修改的结点属性(键值对组成的对象)。
示例：   {libID: 3, nodeID: 5, create: {....}}
        {libID: 3, nodeID: 5, delete: true}
        {libID: 3, nodeID: 5, update: {nodeName: 'xxx', children: [...]} }
------------------------------------------------------------------------------*/
async function saveBlock(data) {
    if (data.create) {
        await blModel.update({libID: data.libID}, {$addToSet: {datas: data.create}});
    }
    if (data.delete) {
        console.log(JSON.stringify(data));
        console.log(data.nodeID);
        await blModel.update({libID: data.libID}, {$pull: {datas: {ID: data.nodeID}}});
        if (data.delete.nodeType == 1){    // 同步删除所有子结点
            await blModel.update({libID: data.libID}, {$pull: {datas: {ParentID: data.nodeID}}});
        }
    }
    else if (data.update){
        let doc = await blModel.findOne({libID: data.libID});
        let datas = doc._doc.datas;
        for (let i = 0; i < datas.length; i++) {
            if (datas[i].ID == data.nodeID) {
                for (let pn in data.update){
                    datas[i][pn] = data.update[pn];
                };
                await doc.save();
                break;
            }
        };
    };
    return 'saveBlock.OK';
};
