"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepareDDFCsvReaderObject = void 0;
var tslib_1 = require("tslib");
var isEmpty = require("lodash.isempty");
var ddf_csv_1 = require("./ddf-csv");
var ddfcsv_error_1 = require("./ddfcsv-error");
var cross_project_diagnostics_1 = require("cross-project-diagnostics");
var lib_1 = require("cross-project-diagnostics/lib");
var github_path_adapter_1 = require("./file-readers/github-path-adapter");
var myName = '';
var myVersion = '';
function prepareDDFCsvReaderObject(defaultResourceReader) {
    return function (externalResourceReader, logger) {
        return {
            init: function (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: function () {
                return { name: this._basePath.slice(this._basePath.indexOf('ddf--')) };
            },
            checkFile: function (path) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var _this = this;
                    return tslib_1.__generator(this, function (_a) {
                        return [2, new Promise(function (resolve, reject) {
                                var status = _this.fileReader.checkFile(path);
                                return resolve({ status: status, url: path });
                            })];
                    });
                });
            },
            getFile: function (filePath, isJsonFile, options) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var _this = this;
                    return tslib_1.__generator(this, function (_a) {
                        return [2, new Promise(function (resolve, reject) {
                                _this.fileReader.readText(filePath, function (err, data) {
                                    if (err) {
                                        return reject(err);
                                    }
                                    try {
                                        if (isJsonFile) {
                                            return resolve(JSON.parse(data));
                                        }
                                        return resolve(data);
                                    }
                                    catch (jsonErr) {
                                        return reject(jsonErr);
                                    }
                                }, options);
                            })];
                    });
                });
            },
            checkIfAssetExists: function (filePath_1) {
                return tslib_1.__awaiter(this, arguments, void 0, function (filePath, repositoryPath) {
                    var assetPath;
                    if (repositoryPath === void 0) { repositoryPath = ''; }
                    return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                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);
                                }
                                assetPath = "".concat(repositoryPath || this._basePath, "/assets/").concat(filePath);
                                return [4, this.checkFile(assetPath)];
                            case 1: return [2, _a.sent()];
                        }
                    });
                });
            },
            getAsset: function (filePath_1) {
                return tslib_1.__awaiter(this, arguments, void 0, function (filePath, repositoryPath) {
                    var assetPath, isJsonAsset;
                    if (repositoryPath === void 0) { repositoryPath = ''; }
                    return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                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);
                                }
                                assetPath = "".concat(repositoryPath || this._basePath, "/").concat(filePath);
                                isJsonAsset = (assetPath).slice(-'.json'.length) === '.json';
                                return [4, this.getFile(assetPath, isJsonAsset)];
                            case 1: return [2, _a.sent()];
                        }
                    });
                });
            },
            read: function (queryParam, parsers, parentDiagnostic) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var diagnostic, _a, debug, error, fatal, result, message, err, err_1;
                    return tslib_1.__generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                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);
                                _a = diagnostic.prepareDiagnosticFor('read'), debug = _a.debug, error = _a.error, fatal = _a.fatal;
                                debug('start reading', queryParam);
                                _b.label = 1;
                            case 1:
                                _b.trys.push([1, 3, , 4]);
                                if (isEmpty(queryParam.repositoryPath) && isEmpty(this._basePath)) {
                                    message = "Neither initial 'path' nor 'repositoryPath' in query were found.";
                                    err = new ddfcsv_error_1.DdfCsvError(message, JSON.stringify(queryParam));
                                    error(message, err);
                                    throw err;
                                }
                                return [4, this.reader.query(queryParam, {
                                        basePath: queryParam.repositoryPath || this._basePath,
                                        fileReader: this.fileReader,
                                        logger: this.logger,
                                        conceptsLookup: new Map(),
                                        diagnostic: diagnostic
                                    })];
                            case 2:
                                result = _b.sent();
                                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);
                                }
                                return [3, 4];
                            case 3:
                                err_1 = _b.sent();
                                fatal('global data reading error', err_1);
                                throw err_1;
                            case 4: return [2, result];
                        }
                    });
                });
            },
            _prettifyData: function (data, parsers) {
                return data.map(function (record) {
                    var keys = Object.keys(record);
                    keys.forEach(function (key) {
                        if (parsers[key]) {
                            record[key] = parsers[key](record[key]);
                        }
                    });
                    return record;
                });
            }
        };
    };
}
exports.prepareDDFCsvReaderObject = prepareDDFCsvReaderObject;
//# sourceMappingURL=ddfcsv-reader.js.map