import { _decorator, Component,Sprite, SpriteFrame} from "cc";
import i18n from "./LanguageData";
import { Logger } from "../../../extend/Logger";
const { ccclass, property } = _decorator;

//图片信息类
@ccclass("SpriteFrameSet")
export class SpriteFrameSet {
    @property
    public language: string = '';
    @property({ type: SpriteFrame })
    public spriteFrame: SpriteFrame | null = null;
}

/**多语言图片
 * 图片多语言 直接挂载LocalizedSprite类 到对应的sprite节点上去
   然后根据languages.length的列表填入如 “en” 然后拖入英文的图片，然后“zh” 拖入中文的图片
 */
@ccclass("LocalizedSprite")
export default class LocalizedSprite extends Component{
    sprite: Sprite | null = null;
    static editor = {
        executeInEditMode: true,
        inspector: 'packages://i18n/inspector/localized-sprite.js',
        menu: 'i18n/LocalizedSprite'
    }

    @property({type: [SpriteFrameSet], displayOrder: 1})
    spriteFrameSet: SpriteFrameSet[] = [];

    public onLoad () {
        this.fetchRender();
    }

    public fetchRender () {
        let sprite = this.getComponent(Sprite);
        if (sprite) {
            this.sprite = sprite;
            this.updateSprite(i18n.curLang);
            return;
        }
    }

    public getSpriteFrameByLang (lang: string) {
        for (let i = 0; i < this.spriteFrameSet.length; ++i) {
            if (this.spriteFrameSet[i].language === lang) {
                return this.spriteFrameSet[i].spriteFrame;
            }
        }
    }

    public updateSprite (language: string) {
        if (!this.sprite) {
            Logger.error('Failed to update localized sprite, sprite component is invalid!');
            return;
        }
        let spriteFrame = this.getSpriteFrameByLang(language);
        if (!spriteFrame && this.spriteFrameSet[0]) {
            spriteFrame = this.spriteFrameSet[0].spriteFrame;
        }
        if (spriteFrame) {
            this.sprite.spriteFrame = spriteFrame;
        }
    }
}


