import fs from 'fs-extra-promise';
import path from 'path';
import { doGlob } from '../util';
import { materialConverters } from './upgrade-material';
import { sceneConverters } from './upgrade-scene';
import { imgdescConverter } from './upgrade-imgdesc';

let rootDir: string;

export type ResourceConfig = {

    group: string[],

    resources: { name: string, type: string, url: string, uuid: string }[]
}



export interface Converters {


    matcher: string;

    converters: Converter[]


}

export interface Converter {

    onStart(rootDir: string): void

    convert(filename: string, v1: any): any

    onFinish(): void
}

export async function run(name: string, sub: string[], options: any) {

    rootDir = sub[0];
    if (rootDir == 'material' || rootDir == 'scene') {
        throw '升级脚本命令已经修改'
    }
    convert(materialConverters);
    convert(imgdescConverter);
    convert(sceneConverters);
}

async function convert(converters: Converters) {
    const list = await doGlob(converters.matcher, rootDir);
    list.map((filepath) => {
        filepath = path.join(rootDir, filepath)
        let json = fs.readJSONSync(filepath);
        if (!json.version) {
            json.version = 1;
        }

        let versionToUpgrade = 1;
        for (let converter of converters.converters) {
            versionToUpgrade++;
            if (json.version < versionToUpgrade) {
                // console.log("升级版本");
                converter.onStart(rootDir)
                const absoluteRootDir = path.join(process.cwd(), rootDir);
                const relativeFilepath = path.relative(absoluteRootDir, filepath)
                // console.log("filepath:" + filepath);
                json = converter.convert(relativeFilepath, json);
                json.version = versionToUpgrade
                fs.writeFileSync(filepath, JSON.stringify(json, null, '\t'), 'utf-8');
                converter.onFinish();
            }
        }
    });
}



class TestUpgrade implements Converters {

    converters: Converter[] = [
        new UpgradeToV2(),
        new UpgradeToV3()


    ]


    matcher: "**/**/*.{mesh.bin,gltf.bin}"


}


class UpgradeToV2 implements Converter {

    onStart(rootDir: string): void {

    }
    convert(filename: string, v1: any) {
        return v1;
    }
    onFinish(): void {

    }


}


class UpgradeToV3 implements Converter {
    onStart(rootDir: string): void {
        console.log('升级到版本3')
    }
    convert(filename: string, v2: any) {
        return v2;
    }
    onFinish(): void {

    }


}