import EventMgr from './EventMgr';
cc.Class({
    extends: cc.Component,

    properties: {
        dragonBone: dragonBones.ArmatureDisplay,
        spfAudioOn: cc.SpriteFrame,
        spfAudioOff: cc.SpriteFrame,
        audRight: cc.AudioClip,
        audWrong: cc.AudioClip,
        audTryagain: cc.AudioClip,
    },

    onLoad() {
        if (this.startPos) {
            this.node.position = this.startPos;
            this.node.scale = this.startScale;
        }
        this.startPos = this.node.position;
        this.startScale = this.node.scale;
        this.nodLight = this.node.getChildByName('light');
        this.nodMask = this.node.getChildByName('mask');
        this.btnAudio = this.node.getChildByName('btnAudio');
        this.btnAudio.on('click', this.onBtnClickAudio, this)
        this.sprAudio = this.btnAudio.getChildByName('sprAudio').getComponent(cc.Sprite);
        this.label = this.node.getChildByName('label').getComponent(cc.Label);
        this.nodCross = this.node.getChildByName('cross');
        this.labelMask = this.node.getChildByName('labelMask');
        this.labelGreen = this.labelMask.getChildByName('labelGreen').getComponent(cc.Label);
        this.nodCross.active = false;
    },

    start() {
        this.init();
    },

    onEnable() {
        this.node.on('touchstart', this.onTouchStart, this);
        EventMgr.on('showAudioButton', this.showAudioButton, this);
    },
    onDisable() {
        this.node.off('touchstart', this.onTouchStart, this);
        EventMgr.off('showAudioButton', this.showAudioButton, this);
    },
    onTouchStart() {
        if (GameData.audioCount != 0) {
            return;
        }
        if (GameData._showDragonbonesMove) {
            return;
        }
        if (GameData._showDragonbones) {
            this.playLabelGreen();
            return;
        }
        if (!GameData.startStepDone) {
            return;
        }
        if (this.isRight) {
            this.chooseRight();
        } else {
            this.chooseWrong();
        }
    },
    showAudioButton() {
        this.btnAudio.active = true;
        this.playShowAudioButton();
    },
    init() {
        this.nodLight.active = false;
        this.nodMask.active = true;
        this.btnAudio.active = false;
    },

    setInfo(data, index, scene, isRight) {
        this.scene = scene;
        this.data = data;
        this.isRight = isRight;
        this.index = index;
        this.loadDragonBone();

        this.label.string = data.text;
        this.labelGreen.string = data.text;
        this.scheduleOnce(() => {
            this.labelMask.x = this.label.node.x - this.label.node.width / 2 * this.label.node.scale;
            this.labelMask.y = this.label.node.y;
        })

        this.label._forceUpdateRenderData();
        if (this.label.node.width > 198) {
            this.label.node.scale = 198 / this.label.node.width;
            this.labelMask.scale = this.label.node.scale;
        }
    },
    loadDragonBone() {
        this.dragonBone.dragonAtlasAsset = null;
        this.dragonBone.dragonAsset = null;
        this.dragonBone.armatureName = '';
        var imageUrl = this.data.optionDragonBone.texPngData.url;
        var skeUrl = this.data.optionDragonBone.skeJsonData.url;
        var atlasUrl = this.data.optionDragonBone.texJsonData.url;
        // imageUrl = 'http://127.0.0.1/NewProject_2_tex.png';
        // skeUrl = 'http://127.0.0.1/NewProject_2_ske.json';
        // atlasUrl = 'http://127.0.0.1/NewProject_2_tex.json';
        // imageUrl = 'http://127.0.0.1/walkingfish_tex.png';
        // skeUrl = 'http://127.0.0.1/walkingfish_ske.json';
        // atlasUrl = 'http://127.0.0.1/walkingfish_tex.json';
        cc.assetManager.loadAny([{ url: atlasUrl, ext: '.txt' }, { url: skeUrl, ext: '.txt' }], (error, assets) => {
            if (error) {
                console.log(error)
            }
            else {
                cc.assetManager.loadRemote(imageUrl, (error, texture) => {
                    if (error) {
                        console.log(error)
                    }
                    else {
                        var atlas = new dragonBones.DragonBonesAtlasAsset();
                        atlas._uuid = atlasUrl;
                        atlas.atlasJson = assets[0];
                        atlas.texture = texture;

                        var asset = new dragonBones.DragonBonesAsset();
                        asset._uuid = skeUrl;
                        asset.dragonBonesJson = assets[1];

                        this.dragonBone.dragonAtlasAsset = atlas;
                        this.dragonBone.dragonAsset = asset;
                        let data = asset._dragonBonesJsonData.armature[0];
                        if (!data) {
                            return;
                        }
                        this.dragonBone.armatureName = data.name;
                        this.animationName = data.animation[0].name;

                        // this.dragonBone.premultipliedAlpha = true;
                        // atlas.texture.setPremultiplyAlpha(true);
                        this.setSpineScale(data.canvas);
                    }
                });
            }
        });
    },

    setSpineScale(size) {
        let bgWidth = 200;
        let bgHeight = 200;
        if (size.width != bgWidth || size.height != bgHeight) {
            let designScale = bgWidth / bgHeight;
            let scale = size.width / size.height;
            if (scale > designScale) {
                this.dragonBone.node.scale = bgWidth / size.width;
            } else {
                this.dragonBone.node.scale = bgHeight / size.height;
            }
        }
    },

    chooseRight() {
        this.nodMask.runAction(cc.fadeOut(1))
        this.showLight();
        this.playAudioRight();
        this.scene.onClickAnswer(this, this.isRight);
    },
    chooseWrong() {
        this.playAudioWrong();
        this.playShowCross();
        this.scene.onClickAnswer(this, this.isRight);
    },

    playAudioRight() {
        GameData.audioCount++;
        let id = cc.audioEngine.play(this.audRight, false, 1);
        cc.audioEngine.setFinishCallback(id, () => {
            GameData.audioCount--;
        })
    },
    playAudioWrong() {
        GameData.audioCount++;
        let id = cc.audioEngine.play(this.audWrong, false, 1);
        cc.audioEngine.setFinishCallback(id, () => {
            GameData.audioCount--;
        })
    },

    playRotateNormal() {
        this.node.runAction(cc.rotateTo(0.5, 0));
    },

    showLight() {
        this.nodLight.active = true;
    },
    playHideAudioButton() {
        this.btnAudio.runAction(
            cc.sequence(
                cc.scaleTo(0.2, 1.2),
                cc.scaleTo(0.4, 0),
                cc.callFunc(() => {

                })
            )
        )
    },
    playShowAudioButton() {
        this.btnAudio.runAction(
            cc.sequence(
                cc.callFunc(() => {
                    this.btnAudio.scale = 0;
                }),
                cc.scaleTo(0.4, 1.2),
                cc.scaleTo(0.2, 1),
                cc.callFunc(() => {

                })
            )
        )
    },

    playShowCross() {
        this.nodCross.active = true;
        this.nodCross.runAction(
            cc.sequence(
                cc.scaleTo(0.1, 1.2),
                cc.scaleTo(0.2, 1),
                cc.callFunc(() => {
                    this.playHideCross();
                })
            )
        )
    },
    playHideCross() {
        this.nodCross.active = true;
        this.nodCross.runAction(
            cc.sequence(
                cc.scaleTo(0.2, 1.2),
                cc.scaleTo(0.4, 0),
                cc.callFunc(() => {
                    this.playAnswerDown();
                })
            )
        )
    },

    playAnswerDown() {
        this.node.runAction(
            cc.spawn(
                cc.rotateBy(1, 720),
                cc.moveBy(1, 0, -1000)
            ),
        )
    },

    playLabelGreen() {
        this.dragonBone.playAnimation(this.animationName, 1);
        this.playAudioOption((duration) => {
            this.scheduleStep = 2;
            this.scheduleDuration = duration / 2 / this.label.node.width * this.scheduleStep;
            if (this.scheduleDuration < 0.05) {
                this.scheduleDuration = 0.05;
                this.scheduleStep = this.scheduleDuration / duration * 2 * this.label.node.width;
            }

            this.unschedule(this.playLabelGreenCb);
            this.unschedule(this.playLabelWhiteCb);
            this.labelMask.anchorX = 0;
            this.labelMask.x = this.label.node.x - this.label.node.width / 2 * this.label.node.scale;
            this.labelMask.width = 0;
            this.labelGreen.node.anchorX = 0;
            this.labelGreen.node.x = 0;
            this.schedule(this.playLabelGreenCb, this.scheduleDuration)

        }, () => {
            this.unschedule(this.changeAudioSpfCb)
            this.sprAudio.spriteFrame = this.spfAudioOn;
            GameData.isAudio = false;
        });
    },
    playLabelGreenCb() {
        this.labelMask.width += this.scheduleStep;
        if (this.labelMask.width >= this.label.node.width) {
            this.unschedule(this.playLabelGreenCb)
            this.labelMask.anchorX = 1;
            this.labelMask.x = this.label.node.x + this.label.node.width / 2 * this.label.node.scale;
            this.labelGreen.node.anchorX = 1;
            this.labelGreen.node.x = 0;
            this.playLabelWhite();
        }
    },
    playLabelWhite() {
        this.unschedule(this.playLabelWhiteCb);
        this.schedule(this.playLabelWhiteCb, this.scheduleDuration)
    },
    playLabelWhiteCb() {
        this.labelMask.width -= this.scheduleStep;
        if (this.labelMask.width <= 0) {
            this.unschedule(this.playLabelWhiteCb)
            this.labelMask.anchorX = 0;
            this.labelMask.x = this.label.node.x - this.label.node.width / 2 * this.label.node.scale;
            this.labelGreen.node.anchorX = 0;
            this.labelGreen.node.x = 0;
        }
    },

    changeAudioSpfCb() {
        this.sprAudio.spriteFrame = this.sprAudio.spriteFrame == this.spfAudioOff ? this.spfAudioOn : this.spfAudioOff;
    },
    onBtnClickAudio() {
        if (GameData.audioCount > 0) {
            return;
        }
        this.sprAudio.spriteFrame = this.spfAudioOff;
        this.schedule(this.changeAudioSpfCb, 0.2)
        this.playAudioOption((duration) => {

        }, () => {
            this.unschedule(this.changeAudioSpfCb)
            this.sprAudio.spriteFrame = this.spfAudioOn;
            GameData.isAudio = false;
        });
    },

    playAudioOption(cb1, cb2) {
        GameData.audioCount++;
        let url = this.data.optionAudio;
        // url = 'http://127.0.0.1/iamflying.mp3';
        cc.assetManager.loadRemote(url, null, (err, clip) => {
            if (err) {
                console.log(err)
                return;
            }
            let id = cc.audioEngine.play(clip, false, 1);
            let duration = cc.audioEngine.getDuration(id);
            cb1 && cb1(duration);
            cc.audioEngine.setFinishCallback(id, () => {
                if (!cc.isValid(this)) {
                    return;
                }
                GameData.audioCount--;
                cb2 && cb2();
            })
        });
    },
    // update (dt) {},
});
