import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class DuiChoosePrefab extends cc.Component {

    @property(cc.Node)
    duiChoose: cc.Node = null;

    @property(cc.Node)
    content: cc.Node = null;

    private hideItemArray: cc.Node[] = [];

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
        this.duiChoose.active = false;
        this.hideItemArray = [];
    }

    setDuiChooseList(answerList: any[]) {
        for (const info of answerList) {
            let duiChoose = this.setItem();
            duiChoose.active = true;
            duiChoose.attr({ iteminfo: info });
            duiChoose.getChildByName("str").getComponent(cc.Label).string = info.str;
        }
    }

    onClick(event) {
        this.content.children.forEach(element => {
            this.setItem(element);
        });
        let target = event.target;
        let index = this.content.children.indexOf(target);
        EventMgr.emitEvent_custom(ryw_Event.DuiChooseResult, { touchIndex: index, duiChooseInfo: target.iteminfo });
    }

    private setItem(target?: cc.Node) {
        if (target) {
            if (this.hideItemArray.indexOf(target) == -1) {
                target.active = false;
                this.hideItemArray.push(target);
            }
            return null;
        } else {
            if (this.hideItemArray.length > 0) {
                return this.hideItemArray.shift();
            }
            let duiChoose = cc.instantiate(this.duiChoose);
            this.content.addChild(duiChoose);
            duiChoose.setPosition(cc.v3());
            return duiChoose;
        }
    }

    // update (dt) {}
}