"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments)).next());
    });
};
const fs = require("fs");
const path = require("path");
const minimatch = require("minimatch");
const injector = require("./yok");
const crypto = require("crypto");
const shelljs = require("shelljs");
const mkdirp = require("mkdirp");
let FileSystem = FileSystem_1 = class FileSystem {
    constructor($injector) {
        this.$injector = $injector;
    }
    zipFiles(zipFile, files, zipPathCallback) {
        return __awaiter(this, void 0, void 0, function* () {
            let $logger = this.$injector.resolve("logger");
            let zipstream = require("zipstream");
            let zip = zipstream.createZip({ level: 9 });
            let outFile = fs.createWriteStream(zipFile);
            zip.pipe(outFile);
            return new Promise((resolve, reject) => {
                outFile.on("error", (err) => reject(err));
                let fileIdx = -1;
                let zipCallback = () => {
                    fileIdx++;
                    if (fileIdx < files.length) {
                        let file = files[fileIdx];
                        let relativePath = zipPathCallback(file);
                        relativePath = relativePath.replace(/\\/g, "/");
                        $logger.trace("zipping as '%s' file '%s'", relativePath, file);
                        zip.addFile(fs.createReadStream(file), { name: relativePath }, zipCallback);
                    }
                    else {
                        outFile.on("finish", () => resolve());
                        zip.finalize((bytesWritten) => {
                            $logger.debug("zipstream: %d bytes written", bytesWritten);
                            outFile.end();
                        });
                    }
                };
                zipCallback();
            });
        });
    }
    unzip(zipFile, destinationDir, options, fileFilters) {
        return __awaiter(this, void 0, void 0, function* () {
            let shouldOverwriteFiles = !(options && options.overwriteExisitingFiles === false);
            let isCaseSensitive = !(options && options.caseSensitive === false);
            let $hostInfo = this.$injector.resolve("$hostInfo");
            this.createDirectory(destinationDir);
            let proc;
            if ($hostInfo.isWindows) {
                proc = path.join(__dirname, "resources/platform-tools/unzip/win32/unzip");
            }
            else if ($hostInfo.isDarwin) {
                proc = "unzip";
            }
            else if ($hostInfo.isLinux) {
                proc = "unzip";
            }
            if (!isCaseSensitive) {
                zipFile = this.findFileCaseInsensitive(zipFile);
            }
            let args = _.flatten(["-b",
                shouldOverwriteFiles ? "-o" : "-n",
                isCaseSensitive ? [] : "-C",
                zipFile,
                fileFilters || [],
                "-d",
                destinationDir]);
            let $childProcess = this.$injector.resolve("childProcess");
            yield $childProcess.spawnFromEvent(proc, args, "close", { stdio: "ignore", detached: true });
        });
    }
    findFileCaseInsensitive(file) {
        let dir = path.dirname(file);
        let basename = path.basename(file);
        let entries = this.readDirectory(dir);
        let match = minimatch.match(entries, basename, { nocase: true, nonegate: true, nonull: true })[0];
        let result = path.join(dir, match);
        return result;
    }
    exists(path) {
        return fs.existsSync(path);
    }
    deleteFile(path) {
        try {
            fs.unlinkSync(path);
        }
        catch (err) {
            if (err && err.code !== "ENOENT") {
                throw (err);
            }
        }
    }
    deleteDirectory(directory) {
        shelljs.rm("-rf", directory);
        const err = shelljs.error();
        if (err !== null) {
            throw new Error(err);
        }
    }
    getFileSize(path) {
        let stat = this.getFsStats(path);
        return stat.size;
    }
    futureFromEvent(eventEmitter, event) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                eventEmitter.once(event, function () {
                    let args = _.toArray(arguments);
                    if (event === "error") {
                        let err = args[0];
                        reject(err);
                        return;
                    }
                    switch (args.length) {
                        case 0:
                            resolve();
                            break;
                        case 1:
                            resolve(args[0]);
                            break;
                        default:
                            resolve(args);
                            break;
                    }
                });
            });
        });
    }
    createDirectory(path) {
        mkdirp.sync(path);
    }
    readDirectory(path) {
        return fs.readdirSync(path);
    }
    readFile(filename, options) {
        return fs.readFileSync(filename, options);
    }
    readText(filename, options) {
        options = options || { encoding: "utf8" };
        if (_.isString(options)) {
            options = { encoding: options };
        }
        if (!options.encoding) {
            options.encoding = "utf8";
        }
        return this.readFile(filename, options);
    }
    readJson(filename, encoding) {
        let data = this.readText(filename, encoding);
        if (data) {
            return JSON.parse(data.replace(/^\uFEFF/, ""));
        }
        return null;
    }
    writeFile(filename, data, encoding) {
        this.createDirectory(path.dirname(filename));
        fs.writeFileSync(filename, data, { encoding: encoding });
    }
    appendFile(filename, data, encoding) {
        fs.appendFileSync(filename, data, { encoding: encoding });
    }
    writeJson(filename, data, space, encoding) {
        if (!space) {
            space = this.getIndentationCharacter(filename);
        }
        return this.writeFile(filename, JSON.stringify(data, null, space), encoding);
    }
    copyFile(sourceFileName, destinationFileName) {
        if (path.resolve(sourceFileName) === path.resolve(destinationFileName)) {
            return;
        }
        this.createDirectory(path.dirname(destinationFileName));
        shelljs.cp("-f", sourceFileName, destinationFileName);
        const err = shelljs.error();
        if (err) {
            throw new Error(err);
        }
    }
    createReadStream(path, options) {
        return fs.createReadStream(path, options);
    }
    createWriteStream(path, options) {
        return fs.createWriteStream(path, options);
    }
    chmod(path, mode) {
        fs.chmodSync(path, mode);
    }
    getFsStats(path) {
        return fs.statSync(path);
    }
    getLsStats(path) {
        return fs.lstatSync(path);
    }
    getUniqueFileName(baseName) {
        if (!this.exists(baseName)) {
            return baseName;
        }
        let extension = path.extname(baseName);
        let prefix = path.basename(baseName, extension);
        for (let i = 2;; ++i) {
            let numberedName = prefix + i + extension;
            if (!this.exists(numberedName)) {
                return numberedName;
            }
        }
    }
    isEmptyDir(directoryPath) {
        let directoryContent = this.readDirectory(directoryPath);
        return directoryContent.length === 0;
    }
    isRelativePath(p) {
        let normal = path.normalize(p);
        let absolute = path.resolve(p);
        return normal !== absolute;
    }
    ensureDirectoryExists(directoryPath) {
        if (!this.exists(directoryPath)) {
            this.createDirectory(directoryPath);
        }
    }
    rename(oldPath, newPath) {
        fs.renameSync(oldPath, newPath);
    }
    renameIfExists(oldPath, newPath) {
        try {
            this.rename(oldPath, newPath);
            return true;
        }
        catch (e) {
            if (e.code === "ENOENT") {
                return false;
            }
            throw e;
        }
    }
    symlink(sourcePath, destinationPath, type) {
        fs.symlinkSync(sourcePath, destinationPath, type);
    }
    setCurrentUserAsOwner(path, owner) {
        return __awaiter(this, void 0, void 0, function* () {
            let $childProcess = this.$injector.resolve("childProcess");
            if (!this.$injector.resolve("$hostInfo").isWindows) {
                let chown = $childProcess.spawn("chown", ["-R", owner, path], { stdio: "ignore", detached: true });
                yield this.futureFromEvent(chown, "close");
            }
        });
    }
    enumerateFilesInDirectorySync(directoryPath, filterCallback, opts, foundFiles) {
        foundFiles = foundFiles || [];
        if (!this.exists(directoryPath)) {
            let $logger = this.$injector.resolve("logger");
            $logger.warn('Could not find folder: ' + directoryPath);
            return foundFiles;
        }
        let contents = this.readDirectory(directoryPath);
        for (let i = 0; i < contents.length; ++i) {
            let file = path.join(directoryPath, contents[i]);
            let stat = this.getFsStats(file);
            if (filterCallback && !filterCallback(file, stat)) {
                continue;
            }
            if (stat.isDirectory()) {
                if (opts && opts.enumerateDirectories) {
                    foundFiles.push(file);
                }
                if (opts && opts.includeEmptyDirectories && this.readDirectory(file).length === 0) {
                    foundFiles.push(file);
                }
                this.enumerateFilesInDirectorySync(file, filterCallback, opts, foundFiles);
            }
            else {
                foundFiles.push(file);
            }
        }
        return foundFiles;
    }
    getFileShasum(fileName, options) {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                let algorithm = (options && options.algorithm) || "sha1";
                let encoding = (options && options.encoding) || "hex";
                let logger = this.$injector.resolve("$logger");
                let shasumData = crypto.createHash(algorithm);
                let fileStream = this.createReadStream(fileName);
                fileStream.on("data", (data) => {
                    shasumData.update(data);
                });
                fileStream.on("end", () => {
                    let shasum = shasumData.digest(encoding);
                    logger.trace(`Shasum of file ${fileName} is ${shasum}`);
                    resolve(shasum);
                });
                fileStream.on("error", (err) => {
                    reject(err);
                });
            });
        });
    }
    readStdin() {
        return __awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => {
                let buffer = '';
                process.stdin.on('data', (data) => buffer += data);
                process.stdin.on('end', () => resolve(buffer));
            });
        });
    }
    rm(options, ...files) {
        shelljs.rm(options, files);
    }
    deleteEmptyParents(directory) {
        let parent = this.exists(directory) ? directory : path.dirname(directory);
        while (this.isEmptyDir(parent)) {
            this.deleteDirectory(parent);
            parent = path.dirname(parent);
        }
    }
    getIndentationCharacter(filePath) {
        if (!this.exists(filePath)) {
            return FileSystem_1.DEFAULT_INDENTATION_CHARACTER;
        }
        let fileContent = this.readText(filePath).trim();
        let matches = fileContent.match(FileSystem_1.JSON_OBJECT_REGEXP);
        if (!matches || !matches[1]) {
            return FileSystem_1.DEFAULT_INDENTATION_CHARACTER;
        }
        let indentation = matches[1];
        return indentation[0] === " " ? indentation : FileSystem_1.DEFAULT_INDENTATION_CHARACTER;
    }
};
FileSystem.DEFAULT_INDENTATION_CHARACTER = "\t";
FileSystem.JSON_OBJECT_REGEXP = new RegExp(`{\\r*\\n*(\\W*)"`, "m");
FileSystem = FileSystem_1 = __decorate([
    injector.register("fs")
], FileSystem);
exports.FileSystem = FileSystem;
var FileSystem_1;
