import { ExtensionType, LoaderParserPriority, utils } from 'pixi.js';
import Locator from '../services/Locator';

interface SpineAssetManifest
{
    data?: {
        spineAtlasFile?: string;
    };
}

interface ManifestBundle
{
    assets: SpineAssetManifest[];
}

interface BundledAssetManifest
{
    bundles?: ManifestBundle[];
}

interface LoaderParseOptions
{
    src: string;
}

const buildAtlasPath = (path: string): string =>
{
    const baseUrl = Locator.network.baseAssetsUrl;

    return baseUrl.endsWith('/') ? `${baseUrl}${path}` : `${baseUrl}/${path}`;
};

/** Injects backend base path into manifest-defined spine atlases. */
export const BasePathInjector = {
    extension: ExtensionType.Asset,
    loader: {
        name: 'BasePathInjector',
        extension: {
            type: ExtensionType.LoadParser,
            priority: LoaderParserPriority.Normal,
        },

        async testParse(asset: BundledAssetManifest, options: LoaderParseOptions): Promise<boolean>
        {
            if (utils.path.extname(options.src).toLowerCase() === '.json' && Array.isArray(asset.bundles))
            {
                for (const bundle of asset.bundles)
                {
                    for (const manifest of bundle.assets ?? [])
                    {
                        if (manifest.data?.spineAtlasFile)
                        {
                            manifest.data.spineAtlasFile = buildAtlasPath(manifest.data.spineAtlasFile);
                        }
                    }
                }
            }

            return false;
        },

        parse(): void
        {
            // no-op parser required by PixiJS extension contract
        },

        unload(): void
        {
            // no-op unload hook required by PixiJS extension contract
        },
    },
} as const;
