import { AudioMgr } from "../../../../main/ViewManage";
import BaseEvent from "../base/BaseEvent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class FBothwayOpen extends BaseEvent {

    /**
     * 控制的栅栏机关
     */
    @property({
        displayName: 'left机关',
        type: cc.Node,
    })
    leftFenceTrigger: cc.Node = null;

    @property({
        displayName: 'right机关',
        type: cc.Node,
    })
    rightFenceTrigger: cc.Node = null;

    @property({
        displayName: '提示图标',
        type: cc.SpriteFrame
    })
    mTipsIcon: cc.SpriteFrame = null;

    @property({
        displayName: "动画",
        type: sp.Skeleton,
    })
    spine: sp.Skeleton = null;

    openType: string = "";

    onBegin(tag) {
        if (tag == 0) {
            this.showOpt(this.mTipsIcon, () => {
                this.spineAction(this.spine, "left", () => {
                    this.openmFenceTrigger(this.leftFenceTrigger, "left");
                })
            })
        } else if (tag == 1) {
            this.showOpt(this.mTipsIcon, () => {
                this.spineAction(this.spine, "right", () => {
                    this.openmFenceTrigger(this.rightFenceTrigger, "right");
                })
            })
        }
    }

    onEnd(tag: number) {
        this.closeOpt();
    }

    openmFenceTrigger(node: cc.Node, type: string) {
        this.pause();
        this.moveCamera(node.getPosition(), 1, () => {
            cc.tween(this.node).sequence(
                cc.callFunc(() => {
                    if (this.openType != type) {
                        this.showFence(node, "close");
                        if (this.openType != "") {
                            this[`${this.openType}FenceTrigger`].active = true;
                            this.showFence(this[`${this.openType}FenceTrigger`], "open");
                        }
                    }
                    this.ff.main.playerEffectByPath(AudioMgr.openDoor);
                }),
                cc.delayTime(1),
                cc.callFunc(() => {
                    this.openType = type;
                    node.active = false;
                    this.resume();
                    this.closeOpt();
                })
            ).start();
        })
    }

    private showFence(element, action) {
        let nodes = element.children;
        for (let i = 0; i < nodes.length; i++) {
            const element = nodes[i];
            let spine: sp.Skeleton = element.getComponent(sp.Skeleton);
            if (spine) {
                spine.setAnimation(0, action, false);
            }
        }
    }

}
