import { _decorator, Component, error } from "cc";
import { EventName } from "../EventName";
import { eventsOnLoad, preloadEvent } from "../Events";
import ResSprite from "../ResSprite";
import I18n, { CountryType } from "./I18n";

const { ccclass, menu, requireComponent } = _decorator;

@ccclass
@eventsOnLoad()
@requireComponent(ResSprite)
@menu("Framework/I18N/LocalizedSprite")
export default class LocalizedSprite extends Component {
    private _sprite: ResSprite = null;
    private _imageKey: string = "";
    /** 图片名 */
    public get imageKey(): string { return this._imageKey; }
    public set imageKey(v: string) {
        if (this._imageKey === v) {
            return;
        }
        this._imageKey = v;
        this.updateSprite();
    }

    protected onLoad(): void {
        try {
            I18n.init();
            this._sprite = this.getComponent(ResSprite);
            if (this._sprite.spriteFrame) {
                this.imageKey = this._sprite.spriteFrame.name;
            }
        } catch (err) {
            error(err);
        }
    }

    @preloadEvent(EventName.UPDATE_LOCALIZED_CMPT)
    public updateSprite(): void {
        if (!this.imageKey) {
            return;
        }
        let url = "";
        switch (I18n.curCountry) {
            case CountryType.ZH:
                url = "texture/localizedImage/zh/";
                break;
            case CountryType.JP:
                url = "texture/localizedImage/jp/";
                break;
            case CountryType.DE:
                url = "texture/localizedImage/de/";
                break;
            case CountryType.FR:
                url = "texture/localizedImage/de/";
                break;
            case CountryType.KR:
                url = "texture/localizedImage/kr/";
                break;
            case CountryType.GB:
                url = "texture/localizedImage/gb/";
                break;
            case CountryType.US:
                url = "texture/localizedImage/us/";
                break;
            case CountryType.CA:
                url = "texture/localizedImage/us/";
                break;
            case CountryType.AU:
                url = "texture/localizedImage/us/";
                break;

            default:
                return;
        }
        url += this.imageKey;
        this._sprite.setSpriteFrame(url + "/spriteFrame");
    }
}
