#!/usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyWebBuildFilesToFlatFolder = void 0;
var promises_1 = __importDefault(require("fs/promises"));
var commander_1 = require("commander");
require("ts-replace-all");
var getAllFiles = function (sourceDirPath, destDirPath, aArrayOfFiles) {
    if (destDirPath === void 0) { destDirPath = ''; }
    if (aArrayOfFiles === void 0) { aArrayOfFiles = []; }
    return __awaiter(void 0, void 0, void 0, function () {
        var files, arrayOfFiles, files_1, files_1_1, file, e_1_1;
        var e_1, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, promises_1.default.readdir(sourceDirPath)];
                case 1:
                    files = _b.sent();
                    arrayOfFiles = aArrayOfFiles || [];
                    _b.label = 2;
                case 2:
                    _b.trys.push([2, 9, 10, 11]);
                    files_1 = __values(files), files_1_1 = files_1.next();
                    _b.label = 3;
                case 3:
                    if (!!files_1_1.done) return [3 /*break*/, 8];
                    file = files_1_1.value;
                    return [4 /*yield*/, promises_1.default.stat(sourceDirPath + "/" + file)];
                case 4:
                    if (!(_b.sent()).isDirectory()) return [3 /*break*/, 6];
                    return [4 /*yield*/, getAllFiles(sourceDirPath + "/" + file, (destDirPath ? destDirPath + "/" : '') + file, arrayOfFiles)];
                case 5:
                    arrayOfFiles = _b.sent();
                    return [3 /*break*/, 7];
                case 6:
                    arrayOfFiles.push((destDirPath ? destDirPath + "/" : '') + file);
                    _b.label = 7;
                case 7:
                    files_1_1 = files_1.next();
                    return [3 /*break*/, 3];
                case 8: return [3 /*break*/, 11];
                case 9:
                    e_1_1 = _b.sent();
                    e_1 = { error: e_1_1 };
                    return [3 /*break*/, 11];
                case 10:
                    try {
                        if (files_1_1 && !files_1_1.done && (_a = files_1.return)) _a.call(files_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7 /*endfinally*/];
                case 11: return [2 /*return*/, arrayOfFiles];
            }
        });
    });
};
var copyWebBuildFilesToFlatFolder = function (sourcePath, destPath, options) { return __awaiter(void 0, void 0, void 0, function () {
    var files, fileMap, _a, _b, _c, index, publicName, localName, destName, e_2_1, modifiedTime, modifiedTimeString;
    var e_2, _d;
    return __generator(this, function (_e) {
        switch (_e.label) {
            case 0: return [4 /*yield*/, promises_1.default.mkdir(destPath, { recursive: true })];
            case 1:
                _e.sent();
                return [4 /*yield*/, getAllFiles(sourcePath, '')];
            case 2:
                files = _e.sent();
                fileMap = [];
                _e.label = 3;
            case 3:
                _e.trys.push([3, 9, 10, 11]);
                _a = __values(files.entries()), _b = _a.next();
                _e.label = 4;
            case 4:
                if (!!_b.done) return [3 /*break*/, 8];
                _c = __read(_b.value, 2), index = _c[0], publicName = _c[1];
                localName = "" + options.base + index.toString() + options.extension;
                destName = destPath + "\\" + localName;
                if (options.debug || options.test) {
                    if (!options.test)
                        console.log("Copying " + publicName + " to " + destName);
                    else
                        console.log("Would copy " + publicName + " to " + destName);
                }
                if (!!options.test) return [3 /*break*/, 6];
                return [4 /*yield*/, promises_1.default.copyFile(sourcePath + '/' + publicName, destName)];
            case 5:
                _e.sent();
                _e.label = 6;
            case 6:
                fileMap.push({ publicName: publicName, localName: localName });
                _e.label = 7;
            case 7:
                _b = _a.next();
                return [3 /*break*/, 4];
            case 8: return [3 /*break*/, 11];
            case 9:
                e_2_1 = _e.sent();
                e_2 = { error: e_2_1 };
                return [3 /*break*/, 11];
            case 10:
                try {
                    if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
                }
                finally { if (e_2) throw e_2.error; }
                return [7 /*endfinally*/];
            case 11:
                modifiedTime = new Date();
                modifiedTimeString = modifiedTime.toDateString() + ' ' + modifiedTime.toTimeString();
                return [4 /*yield*/, promises_1.default.writeFile(destPath + ("\\" + options.json), JSON.stringify({ fileMap: fileMap, date: modifiedTimeString }, undefined, 2))];
            case 12:
                _e.sent();
                return [2 /*return*/];
        }
    });
}); };
exports.copyWebBuildFilesToFlatFolder = copyWebBuildFilesToFlatFolder;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
var sprintf = function (strings) {
    var indices = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        indices[_i - 1] = arguments[_i];
    }
    return function () {
        var values = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            values[_i] = arguments[_i];
        }
        return strings.reduce(function (total, part, index) {
            return total + part + (values[indices[index]] || '');
        }, '');
    };
};
var defaultSource = './';
var defaultTarget = './output';
commander_1.program
    .name('flatify')
    .description('CLI to flatten a source folder with hierarchical folder structure to a flat list of numbered files in a target folder. A JSON file is also output containing an array of the original names.')
    .version('0.0.0')
    .option('-b, --base <name>', 'Flat file base name', 'file')
    .option('-e, --extension <ext>', 'Flat file extension', '.bin')
    .option('-j, --json <name>', 'JSON file name', 'files.json')
    .option('-d, --debug', 'Debug info')
    .option('-t, --test', 'Display files but do not copy')
    .argument('[source]', 'source folder', defaultSource)
    .argument('[target]', 'target folder', defaultTarget)
    .action(function (source, target, options, command) { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, exports.copyWebBuildFilesToFlatFolder(source, target, options)];
            case 1:
                _a.sent();
                return [2 /*return*/];
        }
    });
}); });
commander_1.program.parse();
//# sourceMappingURL=cli.js.map