/**
  * ******************************************************
  *                                                       *
  *   Copyright (C) Microsoft. All rights reserved.       *
  *                                                       *
  * ******************************************************
  */
"use strict";
const fs = require("fs");
const path = require("path");
var archiver = require("archiver");
const child_process = require("child_process");
var spawnSync = require("child_process").spawnSync;
var tmp = require("tmp");
const utils = require("vcremote-utils");
const nconf = require("nconf");
var resources = utils.ResourcesManager;
const project = require("../projectsystem/project");
var VCRemoteLib;
(function (VCRemoteLib) {
    // Will use /localization directory with translated strings if exists in npm installation, otherwise use default english strings.
    var pathToLocalizedStrings = path.join(__dirname + "../../../../", "localization/app/localization/i18n");
    if (fs.existsSync(pathToLocalizedStrings)) {
        resources.init(nconf.get("lang"), pathToLocalizedStrings);
    }
    else {
        resources.init(nconf.get("lang"), path.join(__dirname, "./resources"));
    }
    function execOpen(req, res) {
        var filepath = req.query.filepath;
        console.info(resources.getStringForLanguage(nconf.get("lang"), "OpeningFile", filepath));
        var child = child_process.spawn("open", [filepath], { detached: true });
        // TODO: get return code back to sender.
        res.end();
    }
    VCRemoteLib.execOpen = execOpen;
    function getFiles(req, res) {
        var buf = [];
        req.on('data', function (data) {
            buf.push(data);
        }).on('end', function () {
            var finalBuffer = Buffer.concat(buf).toString();
            var jsonContent = JSON.parse(finalBuffer);
            var incremental = false;
            incremental = Boolean(jsonContent.incremental);
            var rootpath = jsonContent.rootpath;
            var filepaths = jsonContent.filepaths;
            var lastSyncTimeFile = rootpath + "/.lastSyncTime";
            var lastSyncTime;
            if (incremental) {
                try {
                    var stats = fs.statSync(lastSyncTimeFile);
                    lastSyncTime = stats.mtime;
                    console.log(resources.getStringForLanguage(nconf.get("lang"), "SyncingDifference", lastSyncTime.toDateString(), lastSyncTime.toTimeString(), lastSyncTimeFile));
                }
                catch (e) {
                    incremental = false;
                    console.log(resources.getStringForLanguage(nconf.get("lang"), "PerformingFullSync", lastSyncTimeFile));
                }
            }
            if (rootpath != null && filepaths != null) {
                var filepathSeperated = filepaths.split(';');
                res.writeHead(200, "OK", {
                    "Content-Type": "application/zip"
                });
                var archive = archiver.create('zip', {});
                archive.pipe(res);
                archive.on('end', function () {
                    if (fileSent > 0) {
                        touchFile(lastSyncTimeFile);
                    }
                    res.end();
                });
                var fileSent = 0;
                for (var i = 0; i < filepathSeperated.length; i++) {
                    var path = filepathSeperated[i];
                    // if path is not rooted, then root it with rootpath.
                    if (path[0] != '/') {
                        path = rootpath + '/' + path;
                    }
                    try {
                        var stats = fs.statSync(path);
                        if (!incremental || stats.mtime > lastSyncTime) {
                            console.info(resources.getStringForLanguage(nconf.get("lang"), "SendingPath", path));
                            if (stats.isDirectory()) {
                                fileSent++;
                                archive.directory(path, path.substring(rootpath.length + 1));
                            }
                            else {
                                fileSent++;
                                archive.file(path, { name: path.substring(rootpath.length + 1), stats: stats });
                            }
                        }
                        else {
                            console.info(resources.getStringForLanguage(nconf.get("lang"), "SkippingPath", path));
                        }
                    }
                    catch (e) {
                        console.info(resources.getStringForLanguage(nconf.get("lang"), "ErrorGettingInfo", path));
                    }
                }
                console.log(resources.getStringForLanguage(nconf.get("lang"), "SendingFiles", fileSent.toString(), filepathSeperated.length.toString()));
                archive.finalize();
            }
        });
    }
    VCRemoteLib.getFiles = getFiles;
    function putFiles(req, res) {
        var projectDir = req.query.directory;
        console.info(resources.getStringForLanguage(nconf.get("lang"), "UnzippingProject", projectDir));
        var resource = new project.RemoteZipResource(req);
        resource.on("extracted", function () {
            res.end();
        });
        resource.on("error", function () {
            res.end();
        });
        resource.retrieve(projectDir);
    }
    VCRemoteLib.putFiles = putFiles;
    function deleteFiles(req, res) {
        var buf = [];
        req.on('data', function (data) {
            buf.push(data);
        }).on('end', function () {
            var finalBuffer = Buffer.concat(buf).toString();
            var jsonContent = JSON.parse(finalBuffer);
            var incremental = false;
            incremental = Boolean(jsonContent.incremental);
            var rootpath = jsonContent.rootpath;
            var filepaths = jsonContent.filepaths;
            console.info(resources.getStringForLanguage(nconf.get("lang"), "CleaningPaths", rootpath, filepaths));
            var filepathSeperated = filepaths.split(';');
            if (rootpath != null && filepaths != null) {
                for (var i = 0; i < filepathSeperated.length; i++) {
                    var path = filepathSeperated[i];
                    // if path is not rooted, then root it with rootpath.
                    if (path[0] != '/') {
                        path = rootpath + '/' + path;
                    }
                    deleteFolderRecursive(path);
                }
            }
            res.end();
        });
    }
    VCRemoteLib.deleteFiles = deleteFiles;
    function deleteFolderRecursive(path) {
        if (fs.existsSync(path)) {
            var files = fs.readdirSync(path);
            files.forEach(function (file, index) {
                var curPath = path + "/" + file;
                if (fs.lstatSync(curPath).isDirectory()) {
                    deleteFolderRecursive(curPath);
                }
                else {
                    fs.unlinkSync(curPath);
                }
            });
            fs.rmdirSync(path);
        }
    }
    ;
    function touchFile(path) {
        if (!fs.existsSync(path))
            fs.writeFileSync(path, "");
        else
            fs.utimesSync(path, new Date(), new Date());
    }
})(VCRemoteLib || (VCRemoteLib = {}));
module.exports = VCRemoteLib;
