"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
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 helpers_1 = require("./helpers");
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* () {
            const $logger = this.$injector.resolve("logger");
            const zipstream = require("zipstream");
            const zip = zipstream.createZip({ level: 9 });
            const outFile = fs.createWriteStream(zipFile);
            zip.pipe(outFile);
            return new Promise((resolve, reject) => {
                outFile.on("error", (err) => reject(err));
                let fileIdx = -1;
                const zipCallback = () => {
                    fileIdx++;
                    if (fileIdx < files.length) {
                        const 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();
            });
        });
    }
    utimes(path, atime, mtime) {
        return fs.utimesSync(path, atime, mtime);
    }
    unzip(zipFile, destinationDir, options, fileFilters) {
        return __awaiter(this, void 0, void 0, function* () {
            const shouldOverwriteFiles = !(options && options.overwriteExisitingFiles === false);
            const isCaseSensitive = !(options && options.caseSensitive === false);
            const $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);
            }
            const args = _.flatten(["-b",
                shouldOverwriteFiles ? "-o" : "-n",
                isCaseSensitive ? [] : "-C",
                zipFile,
                fileFilters || [],
                "-d",
                destinationDir]);
            const $childProcess = this.$injector.resolve("childProcess");
            yield $childProcess.spawnFromEvent(proc, args, "close", { stdio: "ignore", detached: true });
        });
    }
    findFileCaseInsensitive(file) {
        const dir = path.dirname(file);
        const basename = path.basename(file);
        const entries = this.readDirectory(dir);
        const match = minimatch.match(entries, basename, { nocase: true, nonegate: true, nonull: true })[0];
        const 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) {
        const 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 () {
                    const args = _.toArray(arguments);
                    if (event === "error") {
                        const 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) {
        const data = this.readText(filename, encoding);
        if (data) {
            return helpers_1.parseJson(data);
        }
        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("-rf", 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;
        }
        const extension = path.extname(baseName);
        const prefix = path.basename(baseName, extension);
        for (let i = 2;; ++i) {
            const numberedName = prefix + i + extension;
            if (!this.exists(numberedName)) {
                return numberedName;
            }
        }
    }
    isEmptyDir(directoryPath) {
        const directoryContent = this.readDirectory(directoryPath);
        return directoryContent.length === 0;
    }
    isRelativePath(p) {
        const normal = path.normalize(p);
        const 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* () {
            const $childProcess = this.$injector.resolve("childProcess");
            if (!this.$injector.resolve("$hostInfo").isWindows) {
                const 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)) {
            const $logger = this.$injector.resolve("logger");
            $logger.warn('Could not find folder: ' + directoryPath);
            return foundFiles;
        }
        const contents = this.readDirectory(directoryPath);
        for (let i = 0; i < contents.length; ++i) {
            const file = path.join(directoryPath, contents[i]);
            const 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) => {
                const algorithm = (options && options.algorithm) || "sha1";
                const encoding = (options && options.encoding) || "hex";
                const logger = this.$injector.resolve("$logger");
                const shasumData = crypto.createHash(algorithm);
                const fileStream = this.createReadStream(fileName);
                fileStream.on("data", (data) => {
                    shasumData.update(data);
                });
                fileStream.on("end", () => {
                    const 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);
        }
    }
    realpath(filePath) {
        return fs.realpathSync(filePath);
    }
    getIndentationCharacter(filePath) {
        if (!this.exists(filePath)) {
            return FileSystem_1.DEFAULT_INDENTATION_CHARACTER;
        }
        const fileContent = this.readText(filePath).trim();
        const matches = fileContent.match(FileSystem_1.JSON_OBJECT_REGEXP);
        if (!matches || !matches[1]) {
            return FileSystem_1.DEFAULT_INDENTATION_CHARACTER;
        }
        const 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;
