/*
功能：节点跟随， 如果没有频繁修改节点属性的需求， 建议改成事件触发。
create by EOD.LSX
*/

const { ccclass, property, executeInEditMode, menu} = cc._decorator;
@ccclass
@executeInEditMode
@menu('Extend/LinkNode')
export class LinkNode extends cc.Component{
    @property({
        type: cc.Node,
        tooltip: "关联的节点",
    })
    private LinkNode = [];

    //坐标偏移记录
    @property({visible: false})
    private PosOffset = [];
    //坐标备份
    private PosBack:cc.Vec3 = null;
    //透明度备份
    private OpacityBack = null;
    //缩放备份
    private ScaleBack = null;

    //根据名字获取节点
    public GetLinkNodeByName(name) {
        for (let index = 0; index < this.LinkNode.length; index++) {
            const node:cc.Node = this.LinkNode[index];
            if(node.name == name) {
                return node;
            }
        }
        return null;
    }

    //批量修改属性
    private SetLinkNodes(func){
        this.LinkNode.forEach((node:cc.Node, index) => {
            if(node) {
                func(node, index);
            }
        });
    }

    //激活时
    onEnable(){
        this.SetLinkNodes((linknode:cc.Node)=>{
            linknode.active = true;
        });
    }

    //禁用时
    onDisable(){
        this.SetLinkNodes((linknode:cc.Node)=>{
            linknode.active = false;
        });
    }

    //更新
    update(dt){
        //编辑器专用代码 1
        if(CC_EDITOR) {
            if(this.node.position.equals(this.PosBack) || !this["firstOpenNode"]) {
                this["firstOpenNode"] = true;
                this.SetLinkNodes((linknode:cc.Node, index) => {
                    this.PosOffset[index] = linknode.position.sub(this.node.position);
                });
            }
        }
        //编辑器专用代码 2

        //透明度跟随
        if(this.OpacityBack != this.node.opacity) {
            this.OpacityBack = this.node.opacity;
            this.SetLinkNodes((linknode:cc.Node) => {
                linknode.opacity = this.OpacityBack;
            });
        }

        //缩放跟随
        let IsScaleChange = false;
        if(this.ScaleBack != this.node.scale) {
            this.ScaleBack = this.node.scale;
            this.SetLinkNodes((linknode:cc.Node) => {
                linknode.scale = this.ScaleBack;
            });
            IsScaleChange = true;
        }

        //坐标跟随
        if(IsScaleChange || !this.node.position.equals(this.PosBack)) {
            this.PosBack = this.node.position;
            this.SetLinkNodes((linknode:cc.Node, index) => {
                let ofpos = this.PosOffset[index] || cc.v3(0,0,0);
                linknode.setPosition(this.PosBack.add(ofpos.mul(this.ScaleBack)));
            });
        }
    }
    
}