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

const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('LocalizedSpine')
export class LocalizedSpine extends Component {
    private spineComponent: sp.Skeleton | null = null;

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

    @property({ tooltip: '默认动画名称' })
    private defaultAnimation: string = '';

    @property({ tooltip: '是否自动播放默认动画' })
    private autoPlay: boolean = true;

    onLoad() {
        if (!I18nManager.instance.getIsReady()) {
            I18nManager.instance.init('en');
        }
        this.fetchRender();
    }

    fetchRender() {
        if (!this.spineComponent) {
            this.spineComponent = this.getComponent(sp.Skeleton);
        }

        if (this.spineComponent) {
            this.updateSpine();
        } else {
            console.warn(`LocalizedSpine: No Spine component found on node ${this.node.name}`);
            this.loadDefaultSpine();
        }
    }

    public updateSpine() {
        if (!this.spineComponent || !this.spineName) return;

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

        // 从I18nManager获取缓存的SpineData
        const cachedSpineData = I18nManager.instance.spineCache.get(cacheKey);
        if (cachedSpineData) {
            this.setNewSpineData(cachedSpineData);
            return;
        }

        // 如果缓存中没有，从resources加载
        const spinePath = `i18nSprite/${currentLanguage}/${this.spineName}_${currentLanguage}`;
        resources.load(spinePath, sp.SkeletonData, (err, spineData) => {
            if (err) {
                console.warn(`Failed to load spine: ${spinePath}`, err);
                this.loadDefaultSpine();
                return;
            }

            if (spineData) {
                // 添加到I18nManager的缓存中
                I18nManager.instance.spineCache.set(cacheKey, spineData);
                this.setNewSpineData(spineData);
            }
        });
    }

    private loadDefaultSpine() {
        const defaultPath = `i18nSpine/en/${this.spineName}_en`;
        const cacheKey = `en_${this.spineName}`;

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

        resources.load(defaultPath, sp.SkeletonData, (err, spineData) => {
            if (err) {
                console.error('Failed to load default spine:', err);
                return;
            }

            if (spineData) {
                I18nManager.instance.spineCache.set(cacheKey, spineData);
                this.setNewSpineData(spineData);
            }
        });
    }

    private setNewSpineData(newData: sp.SkeletonData) {
        if (this.spineComponent) {
            this.spineComponent.skeletonData = newData;

            // 如果设置了默认动画且启用了自动播放，则播放默认动画
            if (this.defaultAnimation && this.autoPlay) {
                this.spineComponent.setAnimation(0, this.defaultAnimation, true);
            }
        }
    }

    public setSpineName(name: string) {
        this.spineName = name;
        this.updateSpine();
    }

    public playAnimation(animName: string, loop: boolean = false) {
        if (this.spineComponent) {
            this.spineComponent.setAnimation(0, animName, loop);
        }
    }

    onDestroy() {
        // 清理组件引用
        if (this.spineComponent) {
            this.spineComponent.skeletonData = null;
        }
        this.spineComponent = null;
    }
}