const { ccclass, property } = cc._decorator;

@ccclass
export default class OptQuestionItem extends cc.Component {

    @property(cc.Label)
    labelIndex: cc.Label = null;

    @property(cc.Label)
    labelQuestion: cc.Label = null;

    private optionNodes: cc.Node[] = [];
    private questionID: number = 0;
    private isMultiOpt: boolean = false
    // LIFE-CYCLE CALLBACKS:
    onLoad() {
        this.optionNodes = []
        for (let i = 1; i <= 8; ++i) {
            let optNode = cc.find("content/opt" + i, this.node)
            let tg = optNode.getComponent(cc.Toggle)
            tg.uncheck()
            this.optionNodes.push(optNode)
        }
    }

    start() {

    }

    loadData(index, data) {
        this.questionID = Number(data.id)
        this.labelIndex.string = "" + index
        this.labelQuestion.string = data.question
        this.isMultiOpt = (Number(data.type) == 2)
        let optionsData = data.options;
        for (let i = 0; i < this.optionNodes.length; ++i) {
            let itemNode = this.optionNodes[i]
            if (i < optionsData.length) {
                itemNode.active = true
                itemNode.getComponent(cc.Label).string = optionsData[i]
            }
            else {
                itemNode.active = false
            }
        }
    }

    reset() {
        for (let i = 0; i < this.optionNodes.length; ++i) {
            let itemNode = this.optionNodes[i]
            let tg = itemNode.getComponent(cc.Toggle)
            tg.uncheck()
        }
    }

    onOptionSelect(toggle: cc.Toggle) {
        if (!this.isMultiOpt) {
            for (let i = 0; i < this.optionNodes.length; ++i) {
                let itemNode = this.optionNodes[i]
                let tg = itemNode.getComponent(cc.Toggle)
                if (tg != toggle) {
                    tg.uncheck()
                }
            }
        }
    }

    onClickRadioButton(evt: cc.Event.EventTouch) {
        let target = evt.currentTarget.parent
        let toggle = target.getComponent(cc.Toggle)
        if (toggle.isChecked) {
            toggle.uncheck()
        }
        else {
            toggle.check()
        }
    }

    getResult() {
        let result = []
        for (let i = 0; i < this.optionNodes.length; ++i) {
            let itemNode = this.optionNodes[i]
            let tg = itemNode.getComponent(cc.Toggle)
            if (tg.isChecked) {
                result.push(i + 1)
            }
        }

        return { id: this.questionID, options: result }
    }
}
