import download from 'download';
import * as fs from 'fs-extra-promise';
import fetch from 'node-fetch';
import * as os from 'os';
import * as path from 'path';
import tar from 'tar';
import { checkEgretProject, modifyJSON } from "./util";



type PackageConfig = {

    tarball: string,
    size: number,
    shasum: string
}

type RawConfig = {

    error: string | undefined

    versions: { [version: string]: { dist: PackageConfig } }

    "dist-tags": { [tag: string]: string }
}

export async function run(name: string, sub: string[], options: any) {
    const firstArg = sub[0];
    if (!firstArg) {
        throw 'no package';
    }
    const arr = firstArg.split('@')
    const packageName = arr[0];
    const tag = arr[1] || "stable";
    const projectRoot = process.cwd();
    checkEgretProject(projectRoot);
    const fullPackageName = `@egret/${packageName}`
    const result = await fetch(`https://registry.npm.taobao.org/${fullPackageName}`)
    const rawConfig = await result.json() as RawConfig;
    if (rawConfig.error) {
        throw rawConfig.error;
    }
    const versionInfo = rawConfig.versions[rawConfig['dist-tags'][tag]];
    if (!versionInfo) {
        throw `missing tag : ${tag}`
    }
    const config = versionInfo.dist as PackageConfig;
    const data = await download(config.tarball);
    extractTarball(data, packageName)

    type TSCONFIG = {
        include: string[]
    };

    type EgretProperty = {
        modules: { name: string, path: string }[]
    };

    modifyJSON<TSCONFIG>('tsconfig.json', (value) => {
        value.include.push(packageName);
        return value;
    })

    modifyJSON<EgretProperty>("egretProperties.json", (value) => {
        const m = { name: packageName, path: `./${packageName}` };
        if (!value.modules.some(item => item.name == m.name)) {
            value.modules.push(m);
        }
        return value;
    });
}


async function extractTarball(data: Buffer, dirname: string) {

    const tempDir = path.join(os.tmpdir(), "test");
    const file = path.join(tempDir, '1.tarball');
    await fs.mkdirpAsync(tempDir)
    await fs.writeFileAsync(file, data);
    const originDir = process.cwd();
    process.chdir(tempDir);
    await tar.x({ file });
    process.chdir(originDir);
    const packageDir = path.join(tempDir, "package");
    const targetDir = path.join(originDir, dirname)
    await fs.moveAsync(packageDir, targetDir)



}