// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { getSpriteFrimeByUrl } from "../util_PK_Game";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PicCell extends cc.Component {

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

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

    @property(cc.Sprite)
    icon: cc.Sprite = null;

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

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

    @property(cc.SpriteFrame)
    rightSp: cc.SpriteFrame = null;

    @property(cc.SpriteFrame)
    wrongSp: cc.SpriteFrame = null;
    isRight: any;
    index: any;
    clickCall: Function;

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    onLoad() {

        this.node.on("click", this.onClickItem, this)
    }
    onClickItem(handle, side) {


        let parent = side == 2 ? this.rightRoot : this.leftRoot;
        if (this.isRight) {

            this.rightNode.active = true;

            let node = new cc.Node();
            node.addComponent(cc.Sprite);
            node.getComponent(cc.Sprite).spriteFrame = this.rightSp;
            node.parent = parent;

        } else {

            this.wrongNode.active = true;
            let node = new cc.Node();
            node.addComponent(cc.Sprite);
            node.getComponent(cc.Sprite).spriteFrame = this.wrongSp;
            node.parent = parent;

        }
        if (handle) {
            this.clickCall && this.clickCall(this.index);
        }
    }
    init(index, url, isRight, callback: Function) {

        this.rightNode.active = false;
        this.wrongNode.active = false;
        this.leftRoot.removeAllChildren();
        this.rightRoot.removeAllChildren();
        this.isRight = isRight;
        this.clickCall = callback;
        this.index = index;
        getSpriteFrimeByUrl(url, (sf: cc.SpriteFrame) => {
            this.icon.spriteFrame = sf;
            this.icon.node.scale = Math.max(360 / this.node.width, 360 / this.node.height)
        })

    }
    // update (dt) {}
}
