import fs from 'fs-extra-promise';
import path from 'path';
import { doGlob } from './util';


type AssetsConfig = {

    url: string

    hashCode: number

    class: string
}

type PrefabOrSceneConfig = {

    assets: AssetsConfig[];

    objects: any[]
}

export async function run(name: string, sub: string[], options: any) {
    console.warn("这是一个实验性功能，随时可能会被移除")
    const rootDir = sub[0] ? sub[0] : ".";
    const resourceRoot = path.join(rootDir, "resource");

    // TODO
    // await checkUnusedAsset(resourceRoot)

    const assets = await getAllAssets(resourceRoot)
    const all = await getAllMeshAndMaterial(resourceRoot);

    const notInAssets = all.filter(item => assets.indexOf(item) == -1)

    await Promise.all(notInAssets.map(async (item) => {
        const filename = path.join(resourceRoot, item)
        await fs.removeAsync(filename);
    }))
}

async function getAllMeshAndMaterial(resourceRoot: string) {
    const list = await doGlob("**/**/*.{gltf.bin,mat.json}", resourceRoot);
    return list;
}

async function getAllAssets(resourceRoot: string) {
    const list = await doGlob("**/**/*.{prefab.json,scene.json}", resourceRoot);
    if (list.length == 0) {
        throw '找不到.scene.json和prefab.json'
    }
    const result: string[] = [];
    await Promise.all(list.map(async (assetFilename) => {
        const content = await fs.readFileAsync(path.join(resourceRoot, assetFilename), 'utf-8');
        const config = JSON.parse(content) as PrefabOrSceneConfig;
        const urls = config.assets.map(item =>
            path.join(path.dirname(assetFilename), item.url).split("\\").join("/")
        );
        urls.forEach(item => {
            if (result.indexOf(item) == -1) {
                result.push(item);
            }
        })
    }))
    return result;

}



async function checkUnusedAsset(resourceRoot: string) {
    const list = await doGlob("**/**/*.{prefab.json,scene.json}", resourceRoot);
    if (list.length == 0) {
        throw '找不到.scene.json和prefab.json'
    }
    await Promise.all(list.map(async (assetFilename) => {
        const content = await fs.readFileAsync(path.join(resourceRoot, assetFilename), 'utf-8');
        const config = JSON.parse(content) as PrefabOrSceneConfig;

        const usedHashCode: number[] = [];
        const assetsHashCode = config.assets.map(item => item.hashCode)

        function walk(json: any) {

            if (typeof json == 'object') {
                for (let key in json) {
                    var value = json[key];
                    if (value.hashCode && Object.keys(value).length == 1) {
                        const hashCode = value.hashCode;
                        if (assetsHashCode.indexOf(hashCode) >= 0) {
                            usedHashCode.push(hashCode)
                        }

                    }
                    walk(value)
                }
            }
        }
        walk(config.objects)

        console.log(assetFilename)

        const material = config.assets.filter(item => item.class == "18")
        const used = material.filter(item => {
            console.log(usedHashCode)
            console.log(item.hashCode)
            return usedHashCode.indexOf(item.hashCode) == -1
        })
        console.log('===================')
        console.log(used.length, material.length)

    }))
}
