module.exports = {

    /**
     * 获取项目中的组件
     * @param {*} event 
     */
    'get-components': function (event) {
        const components = getComponents();
        event.reply(null, components);
    },

    /**
     * 添加组件到指定节点
     * @param {*} event 
     * @param {string[]} uuids 节点 Uuid
     * @param {string} name 组件名
     */
    'add-component': function (event, uuids, name) {
        const componentId = getComponentId(name);
        if (!componentId) {
            event.reply(false);
            return;
        }

        Editor.Ipc.sendToPanel('scene', 'scene:add-component', uuids, componentId);
        event.reply(true);
        setTimeout(() => {
            addAffer(uuids, name)
        }, 1000);
    },

};

function addAffer(uuids, name){
    
    if(name == 'cc.Widget') {
        let node = sceneUtil.findNode(uuids[0]);
        let widget = node.getComponent(cc.Widget);
        if(widget){
            widget.isAlignTop = true;
            widget.isAlignBottom = true;
            widget.isAlignLeft = true;
            widget.isAlignRight = true;
            widget.top = 0;
            widget.bottom = 0;
            widget.left = 0;
            widget.right = 0;
        }
    }
}

let sceneUtil = {
    // 检测场景是否存在该子节点并返回相关信息
    findNode(select_uuid)
    {
        var canvas  = cc.director.getScene();
        var ret_node 
        if (canvas && select_uuid) {
            this.getNodeChildren(canvas,(node)=>{
                if (node.uuid == select_uuid){
                    ret_node = node;
                    return ret_node;
                }
            })
        }
        return ret_node;
    },

    // 遍历所有深层子节点
    getNodeChildren(node,callFunc)
    {
        if (!node) return;
        let nodes = node.getChildren();
        nodes.forEach((v)=>{
            v._path_str = (node._path_str || node.name)+"/" + v.name;
            this.getNodeChildren(v,callFunc)
        });
        callFunc(node)
    },
}

/**
 * 获取项目中的组件
 * @returns {string[]}
 */
function getComponents() {
    const items = cc._componentMenuItems,
        components = items.map(v => cc.js.getClassName(v.component));
    return components;
}

/**
 * 获取组件 id
 * @param {string} name 组件名称
 * @returns {string}
 */
function getComponentId(name) {
    // const items = cc._componentMenuItems;
    // for (let i = 0, l = items.length; i < l; i++) {
    //     const { component } = items[i];
    //     if (cc.js.getClassName(component) === name) {
    //         return cc.js._getClassId(component);
    //     }
    // }
    // return null;
    const component = cc.js.getClassByName(name);
    if (component) {
        return cc.js._getClassId(component);
    }
    return null;
}
