import { HttpProject, HttpProjectKind, LegacyDataExportToApiProject, Project, PostmanDataTransformer } from "@api-client/core/build/browser.js";
import { ArcPouchTransformer } from "@api-client/core/build/legacy.js";
const PostmanV20Schema = 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json';
const PostmanV21Schema = 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json';
/**
 * A helper class that controls data import logic.
 */
export class DataImportProcessor {
    #abortCtrl;
    constructor() {
        this.#abortCtrl = new AbortController();
        this.signal = this.#abortCtrl.signal;
    }
    abort() {
        this.#abortCtrl.abort();
    }
    async fromFile(file) {
        this.importData = undefined;
        this.analysis = undefined;
        const contents = await file.text();
        let data;
        try {
            data = JSON.parse(contents);
        }
        catch (e) {
            // ...
        }
        return this.analyzeData(data);
    }
    async importProject(db, space, parent) {
        const { importData, analysis } = this;
        if (!importData || !analysis) {
            throw new Error(`You need to initialize import first.`);
        }
        if (analysis.error) {
            throw new Error(`The import data are invalid.`);
        }
        switch (analysis.source) {
            case 'arc':
                this.importArcProject(importData, db, space, parent);
                break;
            case 'api-client':
                this.importHttpProject(importData, db, space, parent);
                break;
            case 'postman':
                this.importPostmanProject(importData, analysis, db, space, parent);
                break;
            default: throw new Error(`Unknown import source: ${analysis.source}.`);
        }
    }
    analyzeData(data) {
        this.importData = data;
        let analysis;
        if (!data) {
            analysis = {
                error: true,
                message: 'Unable to parse the input file. Not a JSON file.'
            };
        }
        else if (this.isHttpProject(data)) {
            analysis = this.analyzeHttpProject(data);
        }
        else if (this.isArcProject(data)) {
            analysis = this.analyzeArcProject(data);
        }
        else if (this.isPostmanCollection(data)) {
            analysis = this.analyzePostman(data);
        }
        else {
            analysis = {
                error: true,
                message: 'Unrecognized file. Expected ARC, Postman, or HTTP Client export.'
            };
        }
        this.analysis = analysis;
        return analysis;
    }
    /**
     * Checks whether the passed data contain Postman collection (v2 or v2.1).
     */
    isPostmanCollection(data) {
        const typed = data;
        if (!typed.info || !typed.info.schema) {
            return false;
        }
        const { schema } = typed.info;
        return [PostmanV20Schema, PostmanV21Schema].includes(schema);
    }
    analyzePostman(data) {
        const typed = data;
        const { schema, name } = typed.info;
        return {
            name: name || 'Unnamed collection',
            source: 'postman',
            version: schema === PostmanV20Schema ? 'v2' : 'v2.1'
        };
    }
    /**
     * Checks whether the passed data contain ARC's project
     */
    isArcProject(data) {
        const typed = data;
        if (typed.kind !== 'ARC#Project') {
            return false;
        }
        return !!typed.projects && typed.projects.length === 1;
    }
    analyzeArcProject(data) {
        const typed = data;
        const [project] = typed.projects;
        return {
            source: 'arc',
            name: project.name,
        };
    }
    /**
     * Checks whether the data is an HttpProject.
     */
    isHttpProject(data) {
        const typed = data;
        return typed.kind === HttpProjectKind;
    }
    analyzeHttpProject(data) {
        const typed = data;
        return {
            source: 'api-client',
            name: typed.info.name || 'Unnamed project',
        };
    }
    async importArcProject(importData, db, space, parent) {
        const transformer = new ArcPouchTransformer(importData);
        const normalized = await transformer.transform();
        const processor = new LegacyDataExportToApiProject();
        const projects = await processor.readProjects(normalized);
        const [data] = projects;
        this.upsert(data, db, space, parent);
    }
    async importHttpProject(importData, db, space, parent) {
        const data = new HttpProject(importData);
        this.upsert(data, db, space, parent);
    }
    async importPostmanProject(importData, analysis, db, space, parent) {
        const data = await PostmanDataTransformer.transform(importData);
        const project = Array.isArray(data) ? data[0] : data;
        this.upsert(project, db, space, parent);
    }
    async upsert(data, db, space, parent) {
        const meta = Project.fromProject(data, space);
        const opts = {};
        if (parent) {
            opts.parent = parent;
        }
        // meta file
        const file = await db.files.add(meta.toJSON(), opts);
        // file contents
        await db.media.add(file.key, data.toJSON(), 'application/json');
    }
}
//# sourceMappingURL=DataImportProcessor.js.map