import { _decorator, Component, Graphics, Label, lerp, macro, misc, Node, Sprite, tween, UI, UITransform } from "cc";
import { Global } from "../Global";

const { ccclass, property, executeInEditMode } = _decorator;

@ccclass("PropBtn")
@executeInEditMode
export class PropBtn extends Component {

    img: Sprite;

    nameTxt: Label;

    cdMask: Graphics;

    cdTxt: Label;

    numTxt: Label;


    private _propNum = 0;
    get propNum() {
        return this._propNum;
    }

    set propNum(value: number) {
        this._propNum = value;
        this.numTxt.string = `${value}`;
    }

    onLoad() {
        this.img = this.node.getChildByName("img").getComponent(Sprite);
        this.nameTxt = this.node.getChildByName("name").getComponent(Label);

        this.numTxt = this.node.getChildByPath("propNum/num")
            .getComponent(Label);

        const cd = this.node.getChildByName("cd");

        this.cdMask = cd.getChildByName("mask").getComponent(Graphics);
        this.cdTxt = cd.getChildByName("num").getComponent(Label);

        this.cdTxt.node.active = false;
        this.cdMask.node.active = false;

        // this.startCd(5);
        // this.drawProcess(0.4);

        this.node.on(Node.EventType.TOUCH_START, this.use, this);

    }

    start() {

    }

    doUse() {

    }

    private use() {
        if (this.cd) {
            return;
        }

        this.doUse();
    }

    drawProcess(process: number) {
        process = misc.clampf(process, 0, 1);

        const h = lerp(0, Math.PI, process);

        this.cdMask.clear();
        this.cdMask.arc(0, 0, 50, h - Math.PI / 2, -h - Math.PI / 2, false);
        this.cdMask.fill();

        // this.cdMask.moveTo(0, )
    }

    totalCd = 0;
    cd = 0;

    startCd() {

        const ps = this.node.parent
            .getComponentsInChildren(PropBtn)
            .map((v) => {
                v.startCdSelf(Global.PROP_CD);
            });

        return Promise.all(ps);
    }

    startCdSelf(cd = 5) {
        return new Promise<void>((resolve) => {
            this.cdTxt.node.active = true;
            this.cdMask.node.active = true;
            this.cd = this.totalCd = cd;
            tween(this as PropBtn)
                .to(cd, { cd: 0 }, {
                    onUpdate: (target: PropBtn, ratio: number) => {
                        this.drawProcess(1 - ratio);
                        const cdStr = this.cd < 10 ? this.cd.toFixed(1) : Math.ceil(this.cd);
                        this.cdTxt.string = `${cdStr}s`;
                    }
                })
                .call(() => {
                    this.cdTxt.node.active = false;
                    this.cdMask.node.active = false;
                    resolve();
                })
                .start();
        });
    }

}


