/**
 * 帧动画.
 */


const { ccclass, property, executeInEditMode } = cc._decorator;

@ccclass
export class SpriteFrames extends cc.Component {

    @property({ tooltip: "一秒播放几张.", min: 1, step: 1, displayName: "帧率." })
    sample: number = 4;

    @property({ tooltip: "是否循环播放.", displayName: "循环." })
    isLoop: boolean = true;

    @property({ tooltip: "自动加载.", displayName: "自动添加帧." })
    isAutoLoad: boolean = false;

    @property({ tooltip: "设置播放的字母按键.", displayName: "播放按键." })
    playKey: string = '';

    @property({ type: [cc.SpriteFrame], tooltip: "帧集合.", displayName: "动画帧.", visible() { return !this.isAutoLoad; } })
    spriteFrames: cc.SpriteFrame[] = [];

    @property({ tooltip: "Bundle名称.", displayName: "动态资源包名称.", visible() { return this.isAutoLoad; } })
    bundleName: string = "Texture";

    @property({ tooltip: "资源路径.", displayName: "文件夹路径名称.", visible() { return this.isAutoLoad; } })
    path: string = "";

    @property({ tooltip: "文件名称前缀.", displayName: "名称前缀.", visible() { return this.isAutoLoad; } })
    fileName: string = "";

    private animation: cc.Animation = null;


    start() {
        this.onAddSprite();
        if (this.isAutoLoad) {
            this.onLoadAssets();
        } else {
            this.onAnimation();
        }

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    private onAddSprite() {
        let sprite = this.node.getComponent(cc.Sprite)
        if (sprite) { return; }
        sprite = this.node.addComponent(cc.Sprite);
        sprite.sizeMode = cc.Sprite.SizeMode.RAW;
        sprite.trim = false;
    }

    private onAnimation() {
        const animation: cc.Animation = this.node.getComponent(cc.Animation) || this.node.addComponent(cc.Animation);

        const clip: cc.AnimationClip = cc.AnimationClip.createWithSpriteFrames(this.spriteFrames, this.sample);
        if (this.isLoop) {
            clip.wrapMode = cc.WrapMode.Loop;
        }
        animation.addClip(clip, "def");
        animation.play("def");

        this.animation = animation;

        // console.log('动画帧集合: ', this.spriteFrames);
    }

    private onLoadAssets() {
        cc.assetManager.loadBundle(this.bundleName, (err, bundle: cc.AssetManager.Bundle) => {
            if (err) {
                window.alert("加载动态资源包错误，请检查 动态资源包名称 参数设置!");
                return console.warn(`===> 加载 ${this.bundleName} 失败, 错误: ${err}`);
            }
            bundle.loadDir(this.path, cc.SpriteFrame, (error, assets: cc.SpriteFrame[]) => {
                if (err) {
                    window.alert("加载文件夹资源文件错误，请检查 文件夹路径名称 参数设置!");
                    return console.warn(`===> 加载资源 ${this.path} 失败, 错误: ${error}`);
                }
                let sfs = [], oldIndex, nextIndex;
                assets.forEach(sf => {
                    if (sf.name.indexOf(this.fileName) > -1) sfs.push(sf);
                });
                sfs = sfs.sort((old, next) => {
                    oldIndex = parseInt(old.name.substr(this.fileName.length, old.name.length));
                    nextIndex = parseInt(next.name.substr(this.fileName.length, next.name.length));
                    return oldIndex - nextIndex;
                });
                this.spriteFrames = sfs;
                this.onAnimation();
            });
        });
    }

    private onKeyDown(event: cc.Event.EventKeyboard) {
        if (!this.playKey || this.playKey.length === 0) { return; }
        if (event.keyCode === cc.macro.KEY[this.playKey]) {
            this.animation.play("def");
        }
    }

}
