import i18n from "../../../../i18n/i18n";
import { SpriteActionType } from "../../object/FSprite";

/**
 * 文字一个个的出现
 */
const {ccclass, property} = cc._decorator;

@ccclass
export default class WOneByone extends cc.Component {
    @property(cc.Label)
    label: cc.Label = null;

    text: string = '';
    
    private indexA = 0;
    private indexB = 0;

    public isOver = true;
    private interval = 100;//字出现间隔100毫秒
    private jumpThis = false;//是否跳过
    private ctime = 0;

    public dialogs:Array<string> = null;
    public spine:sp.Skeleton = null;

    public callback:()=>void;

    public setCallback(callback:()=>void){
        this.callback = callback;
    }
    public _start(){
        this.jumpThis = false;
        this.indexA = 0;
        this.nextAction();
    }
    update(dt){
        if(this.isOver){
            return;
        }
        if(this.jumpThis){
            this.showWorld();
        }else{
            let time = new Date().getTime();
            if(time - this.ctime > this.interval){
                this.ctime = time;
                this.showWorld();
            }
        }
    }
    public reset(){
        this.indexA = 0;
        this.indexB = 0;
        this.label.string = '';
        this.isOver = false;
        this.jumpThis = false;
    }
    public jump(){
        if(this.isOver){
            this.indexA ++;
            if(this.indexA >= this.dialogs.length){
                this.callback();
                return;
            }
            this.nextAction();
            return;
        }
        this.jumpThis = true;
    }
    private showWorld(){
        if(this.indexB >= this.text.length){
            this.isOver = true;
            return;
        }
        this.indexB ++;
        let tmp = this.text.substring(0,this.indexB);
        this.label.string = tmp;
    }
    //执行下一个动作
    private nextAction(){
        this.indexB = 0;
        this.text = i18n.t(this.dialogs[this.indexA]);
        this.jumpThis = false;

        //判断是表情还是文字
        if(this.text.indexOf('#') == 0){//第一个字符为#表示表情
            if(this.spine){
                this.node.children[0].active = false;
                this.spine.setCompleteListener(()=>{
                    this.spine.setCompleteListener(null);
                    this.node.children[0].active = true;
                    this.spine.setAnimation(0, SpriteActionType.stand, true);
                    this.jump();
                })
                let action = this.text.replace('#','');
                this.spine.setAnimation(0,action, false);
            }else{
                this.jump();
            }
        }else{
            this.isOver = false;
        }
    }

}
