import { Converter, Converters, ResourceConfig } from ".";
import path from 'path';
import fs from 'fs';

type ImgdescConfig = {


    name: string
}


/**
 * 将 name 属性从相对路径修改为 resName
 */
class ImgdescConverter implements Converter {


    private resourceConfigJson!: ResourceConfig;

    onStart(rootDir: string): void {
        const resourceFile = path.join(rootDir, 'default.res.json');
        const content = fs.readFileSync(resourceFile, 'utf-8');
        this.resourceConfigJson = JSON.parse(content) as ResourceConfig;
    }
    convert(filename: string, v1: ImgdescConfig) {
        const absoluteUrl = path.join(path.dirname(filename), v1.name).split("\\").join("/")
        const resName = this.getResName(filename, absoluteUrl);
        v1.name = resName;
        return v1;
    }

    private getResName(filename: string, url: string) {
        const result = this.resourceConfigJson.resources.find((item) => item.url == url);
        if (result) {
            return result.name
        }
        else {
            throw new Error(`missing ${url} in ${filename}`)
        }
    }
    onFinish(): void {

    }



}

export const imgdescConverter: Converters = {

    matcher: "**/**/*.imgdesc.json",

    converters: [new ImgdescConverter()]
}