import { _decorator, Component, Node, find } from 'cc';
import { BaseUI } from './BaseUI';
const { ccclass, property } = _decorator;

@ccclass('ComponentEx')
export class ComponentEx extends Component {

    protected _findInChildren(node: Node, name: string): Node|null {
        var x = node.getChildByName(name);
        if (x) return x;
        if (node.children.length == 0) return null;

        for (var i = 0; i < node.children.length; ++i) {
            var tmp = this._findInChildren(node.children[i], name);
            if (tmp) return tmp;
        }
        return null;
    }

    protected m_objects: Map<string, any> = new Map<string, any>();
    public GetNode(name: string, refind: boolean = false): Node {
        if (!refind) {
            if (this.m_objects && this.m_objects.has(name)) return this.m_objects.get(name);
            if (name == this.node.name) return this.node;
        }

        if (name.indexOf("/") != -1) {
            var tmp = find(name, this.node) as any;
            if (tmp) this.m_objects.set(name,tmp);
            return tmp;
        }
        else {
             tmp = this._findInChildren(this.node, name);
            if (tmp) this.m_objects.set(name,tmp);
            return tmp;
        }
    }

    //从Canvas开始寻找节点
    public GetNodeFromCanvas(name: string): Node {
        let bui = find("Canvas").getComponent(ComponentEx);
        if(!bui)
            bui = find("Canvas").getComponentInChildren(ComponentEx);
        return bui.GetNode(name);
    }

    // @ts-ignore
    public findComponentInParent<T extends Component>(node: Node, ctor: typeof T) {
        let parent: Node|null = node;
        while (parent) {
            let comp = parent.getComponent(ctor);
            if (comp) return comp;
            parent = parent.parent;
        }
        return null;
    }
}
