"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareDDFCsvReaderObject = void 0;
const isEmpty = require("lodash.isempty");
const ddf_csv_1 = require("./ddf-csv");
const ddfcsv_error_1 = require("./ddfcsv-error");
const cross_project_diagnostics_1 = require("cross-project-diagnostics");
const lib_1 = require("cross-project-diagnostics/lib");
const github_path_adapter_1 = require("./file-readers/github-path-adapter");
const myName = '@vizabi/reader-ddfcsv';
const myVersion = '4.3.11';
function prepareDDFCsvReaderObject(defaultResourceReader) {
    return function (externalResourceReader, logger) {
        return {
            init(readerInfo) {
                this._basePath = (0, github_path_adapter_1.githubPathAdapter)(readerInfo.path || '');
                this._lastModified = readerInfo._lastModified;
                this.fileReader = externalResourceReader || defaultResourceReader;
                this.logger = logger;
                this.resultTransformer = readerInfo.resultTransformer;
                this.readerOptions = {
                    basePath: this._basePath,
                    fileReader: this.fileReader,
                    logger: this.logger,
                };
                this.reader = (0, ddf_csv_1.ddfCsvReader)(this.logger);
            },
            getDatasetInfo() {
                return { name: this._basePath.slice(this._basePath.indexOf('ddf--')) };
            },
            async checkFile(path) {
                return new Promise((resolve, reject) => {
                    const status = this.fileReader.checkFile(path);
                    return resolve({ status, url: path });
                });
            },
            async getFile(filePath, isJsonFile, options) {
                return new Promise((resolve, reject) => {
                    this.fileReader.readText(filePath, (err, data) => {
                        if (err) {
                            return reject(err);
                        }
                        try {
                            if (isJsonFile) {
                                return resolve(JSON.parse(data));
                            }
                            return resolve(data);
                        }
                        catch (jsonErr) {
                            return reject(jsonErr);
                        }
                    }, options);
                });
            },
            async checkIfAssetExists(filePath, repositoryPath = '') {
                if (isEmpty(repositoryPath) && isEmpty(this._basePath)) {
                    throw new ddfcsv_error_1.DdfCsvError(`Neither initial 'path' nor 'repositoryPath' as a second param were found.`, `Happens in 'checkIfAssetExists' function`, filePath);
                }
                const assetPath = `${repositoryPath || this._basePath}/assets/${filePath}`;
                return await this.checkFile(assetPath);
            },
            async getAsset(filePath, repositoryPath = '') {
                if (isEmpty(repositoryPath) && isEmpty(this._basePath)) {
                    throw new ddfcsv_error_1.DdfCsvError(`Neither initial 'path' nor 'repositoryPath' as a second param were found.`, `Happens in 'getAsset' function`, filePath);
                }
                const assetPath = `${repositoryPath || this._basePath}/${filePath}`;
                const isJsonAsset = (assetPath).slice(-'.json'.length) === '.json';
                return await this.getFile(assetPath, isJsonAsset);
            },
            async read(queryParam, parsers, parentDiagnostic) {
                const diagnostic = parentDiagnostic ?
                    (0, cross_project_diagnostics_1.createDiagnosticManagerOn)(myName, myVersion).basedOn(parentDiagnostic) :
                    (0, cross_project_diagnostics_1.createDiagnosticManagerOn)(myName, myVersion).forRequest('').withSeverityLevel(lib_1.Level.OFF);
                const { debug, error, fatal } = diagnostic.prepareDiagnosticFor('read');
                let result;
                debug('start reading', queryParam);
                try {
                    if (isEmpty(queryParam.repositoryPath) && isEmpty(this._basePath)) {
                        const message = `Neither initial 'path' nor 'repositoryPath' in query were found.`;
                        const err = new ddfcsv_error_1.DdfCsvError(message, JSON.stringify(queryParam));
                        error(message, err);
                        throw err;
                    }
                    result = await this.reader.query(queryParam, {
                        basePath: queryParam.repositoryPath || this._basePath,
                        fileReader: this.fileReader,
                        logger: this.logger,
                        conceptsLookup: new Map(),
                        diagnostic
                    });
                    result = parsers ? this._prettifyData(result, parsers) : result;
                    if (this.resultTransformer) {
                        result = this.resultTransformer(result);
                    }
                    if (this.logger && this.logger.log) {
                        logger.log(JSON.stringify(queryParam), result.length);
                        logger.log(result);
                    }
                }
                catch (err) {
                    fatal('global data reading error', err);
                    throw err;
                }
                return result;
            },
            _prettifyData(data, parsers) {
                return data.map(record => {
                    const keys = Object.keys(record);
                    keys.forEach(key => {
                        if (parsers[key]) {
                            record[key] = parsers[key](record[key]);
                        }
                    });
                    return record;
                });
            }
        };
    };
}
exports.prepareDDFCsvReaderObject = prepareDDFCsvReaderObject;
//# sourceMappingURL=ddfcsv-reader.js.map