import { _decorator, Component, SpriteFrame, Sprite, resources } from 'cc';
import { I18nManager } from '../manager/I18nManager';

const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('LocalizedSprite')
export class LocalizedSprite extends Component {
    private sprite: Sprite | null = null;

    @property({ tooltip: '资源名字' })
    private spriteName: string = '';

    onLoad() {
        if (I18nManager.instance.getIsReady()) {
            this.fetchRender();
        }
    }

    fetchRender() {
        if (!this.sprite) {
            this.sprite = this.getComponent(Sprite);
        }

        if (this.sprite) {
            this.updateSprite();
        } else {
            console.warn(`LocalizedSprite: No Sprite component found on node ${this.node.name}`);
            this.loadDefaultSprite();
        }
    }

    public updateSprite() {
        if (!this.sprite || !this.spriteName) return;

        const currentLanguage = I18nManager.instance.currentLanguage;
        const cacheKey = `${currentLanguage}_${this.spriteName}`;

        // 从I18nManager获取缓存的SpriteFrame
        const cachedFrame = I18nManager.instance.spriteFrameCache.get(cacheKey);
        if (cachedFrame) {
            this.setNewSpriteFrame(cachedFrame);
            return;
        }

        // 如果缓存中没有，从resources加载
        const spritePath = `i18nSprite/${currentLanguage}/${this.spriteName}/spriteFrame`;
        resources.load(spritePath, SpriteFrame, (err, spriteFrame) => {
            if (err) {
                console.warn(`Failed to load sprite: ${spritePath}`, err);
                this.loadDefaultSprite();
                return;
            }

            if (spriteFrame) {
                // 添加到I18nManager的缓存中
                I18nManager.instance.spriteFrameCache.set(cacheKey, spriteFrame);
                this.setNewSpriteFrame(spriteFrame);
            }
        });
    }

    private loadDefaultSprite() {
        const defaultPath = `i18nSprite/en/${this.spriteName}/spriteFrame`;
        const cacheKey = `en_${this.spriteName}`;

        // 从I18nManager获取默认语言的缓存
        const cachedFrame = I18nManager.instance.spriteFrameCache.get(cacheKey);
        if (cachedFrame) {
            this.setNewSpriteFrame(cachedFrame);
            return;
        }

        resources.load(defaultPath, SpriteFrame, (err, spriteFrame) => {
            if (err) {
                console.error('Failed to load default sprite:', err);
                return;
            }

            if (spriteFrame) {
                // 添加到I18nManager的缓存中
                I18nManager.instance.spriteFrameCache.set(cacheKey, spriteFrame);
                this.setNewSpriteFrame(spriteFrame);
            }
        });
    }

    private setNewSpriteFrame(newFrame: SpriteFrame) {
        if (this.sprite) {
            this.sprite.spriteFrame = newFrame;
        }
    }

    public setSpriteName(name: string) {
        this.spriteName = name;
        this.updateSprite();
    }

    onDestroy() {
        // 只清理当前组件的引用
        if (this.sprite) {
            this.sprite.spriteFrame = null;
        }
        this.sprite = null;
    }
}