/**
* ******************************************************
*                                                       *
*   Copyright (C) Microsoft. All rights reserved.       *
*                                                       *
* ******************************************************
*/
/// <reference path="../typings/node.d.ts" />
/// <reference path="../typings/Q.d.ts" />
/// <reference path="../typings/vcremote-utils.d.ts" />
/// <reference path="../typings/express.d.ts" />
/// <reference path="../typings/semver.d.ts" />
"use strict";
var q = require("q");
var projects = require("./projectsystem/project-collection");
var project = require("./projectsystem/project");
var build = require("./projectsystem/build");

var fs = require("fs");

var dd = require("./projectsystem/device-discovery");
var xmlbuilder = require("xmlbuilder");
var ioslib = require('ioslib');

var VCRemoteLib;
(function (VCRemoteLib) {
    var VCLanguageSpecificsResponse = (function () {
        function VCLanguageSpecificsResponse(projects, request) {
            this._projects = projects;
            this._request = request;
        }
        VCLanguageSpecificsResponse.prototype.renderDevices = function (res) {
            var devices = new dd.DeviceDiscovery();
            var project = xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up();
            q.all([devices.getDevices(), devices.getSimulators()]).spread(function (deviceResults, simulatorResults) {
                var devicesElement = project.ele("devices", { "count": deviceResults.length });
                var simulatorsElement = project.ele("simulators", { "count": simulatorResults.length });
                for (var i = 0; i < deviceResults.length; i++) {
                    devicesElement.ele("device", { "udid": deviceResults[i].udid }).ele("name", deviceResults[i].name).up().ele("arch", deviceResults[i].cpuArchitecture).up();
                }
                for (var i = 0; i < simulatorResults.length; i++) {
                    simulatorsElement.ele("device", { "udid": simulatorResults[i].udid }).ele("name", simulatorResults[i].name).up().ele("arch", simulatorResults[i].cpuArchitecture).up();
                }
                res.send(200, project.end({ pretty: true }));
            });
        };

        VCLanguageSpecificsResponse.prototype.renderProjects = function (res) {
            var self = this;
            var send = function (pps) {
                var result = xmlbuilder.create("projectCollection").ele("version", self._projects.version).up().ele("minimumSupportedClientVersion", self._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", self._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("userDirectory", self._projects.userDirectory).up().ele(pps).up().end({ pretty: true });
                res.send(200, result);
            };

            this._projects.provisioningProfiles.provisioningProfiles.then(function (profiles) {
                // Convert provisioning profiles into xmlbuild friendly format for encoding.
                var pps = {
                    provisioningProfiles: function () {
                        var pps = [];
                        profiles.forEach(function (pp) {
                            pps.push({ provisioningProfile: pp });
                        });
                        return pps;
                    }
                };
                send(pps);
            }, function (error) {
                console.log(error);
                send({ provisioningProfiles: [] });
            });
        };

        VCLanguageSpecificsResponse.prototype.renderIncompatibleClient = function (res) {
            res.send(200, xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[1 /* FAILURE */]).up().ele("code", projects.ProjectCollectionError[1 /* INCOMPATIBLE */]).up().ele("message", "The client is incompatible with current version of this build agent.").up().end({ pretty: true }));
        };

        VCLanguageSpecificsResponse.prototype.renderProjectInfo = function (res, prj) {
            var stateHistory = prj.history.map(function (e) {
                return project.ProjectState[e];
            }).reduce(function (prev, curr) {
                return prev + "," + curr;
            });
            res.send(200, xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("storeDirectory", this._projects.storeDirectory).up().ele("userDirectory", this._projects.userDirectory).up().ele("project", { id: prj.id }).ele("projectDirectory", prj.directory).up().ele("state", project.ProjectState[prj.state]).up().ele("stateHistory", stateHistory).up().end({ pretty: true }));
        };

        VCLanguageSpecificsResponse.prototype.renderProjectCfg = function (res, cfg) {
            res.send(xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("storeDirectory", this._projects.storeDirectory).up().ele("userDirectory", this._projects.userDirectory).up().ele("project", { id: cfg.project.id }).ele("projectDirectory", cfg.project.directory).up().ele("configuration", { id: cfg.id }).ele("outputDirectory", cfg.outputDirectory).up().ele("name", cfg.config).up().ele("arch", cfg.arch).up().ele("sdk", cfg.sdk).up().end({ pretty: true }));
        };

        VCLanguageSpecificsResponse.prototype.renderProjectCfgs = function (res, prj) {
            res.writeHead(200, "OK", { 'Content-Type': 'text/xml' });
            var project = xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("storeDirectory", this._projects.storeDirectory).up().ele("userDirectory", this._projects.userDirectory).up().ele("project", { id: prj.id }).ele("projectDirectory", prj.directory).up();
            var cfgs = prj.build.all;
            for (var i = 0; i < cfgs.length; i++) {
                project.ele("configuration", { id: cfgs[i] }).ele("outputDirectory", cfgs[i].outputDirectory).up().ele("logFileName", cfgs[i].logFileName).up().ele("name", cfgs[i].config.config).up().ele("arch", cfgs[i].config.arch).up().ele("sdk", cfgs[i].config.sdk).up().ele("build").ele("state", build.BuildState[cfgs[i].state]);
            }
            res.write(project.end({ pretty: true }));
            res.end();
        };

        VCLanguageSpecificsResponse.prototype.renderBuildInfo = function (res, bld) {
            res.writeHead(200, "OK", { 'Content-Type': 'text/xml' });
            res.write(xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("storeDirectory", this._projects.storeDirectory).up().ele("userDirectory", this._projects.userDirectory).up().ele("project", { id: bld.project.id }).ele("projectDirectory", bld.project.directory).up().ele("configuration", { id: bld.config.id }).ele("outputDirectory", bld.outputDirectory).up().ele("logFileName", bld.logFileName).up().ele("name", bld.config.config).up().ele("arch", bld.config.arch).up().ele("sdk", bld.config.arch).up().ele("build").ele("state", build.BuildState[bld.state]).up().ele("result", build.BuildResult[bld.result]).up().up().end({ pretty: true }));
            res.end();
        };

        VCLanguageSpecificsResponse.prototype.renderBuild = function (res, bld) {
            res.writeHead(200, "OK", {
                "Content-Type": "application/zip",
                "Content-Length": fs.statSync(bld.archiveFileName).size
            });
            fs.createReadStream(bld.archiveFileName).pipe(res);
        };

        VCLanguageSpecificsResponse.prototype.renderBuildLog = function (res, bld, log, pos) {
            res.writeHead(200, "OK", { "Content-Type": "text/xml" });
            res.write(xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("storeDirectory", this._projects.storeDirectory).up().ele("userDirectory", this._projects.userDirectory).up().ele("project", { id: bld.project.id }).ele("projectDirectory", bld.project.directory).up().ele("configuration", { id: bld.id }).ele("outputDirectory", bld.outputDirectory).up().ele("logFileName", bld.logFileName).up().ele("name", bld.config.config).up().ele("arch", bld.config.arch).up().ele("sdk", bld.config.sdk).up().ele("build").ele("state", build.BuildState[bld.state]).up().ele("result", build.BuildResult[bld.result]).up().ele("log", { pos: pos, length: log.length, available: bld.log.size }).dat(log).up().up().end({ pretty: true }));
            res.end();
        };

        VCLanguageSpecificsResponse.prototype.renderBuildStatus = function (res, prj, bld) {
            res.writeHead(200, "OK", { "Content-Type": "text/xml" });
            var project = xmlbuilder.create("projectCollection").ele("version", this._projects.version).up().ele("minimumSupportedClientVersion", this._projects.minimumSupportedClientVersion).up().ele("maximumSupportedClientVersion", this._projects.maximumSupportedClientVersion).up().ele("status", projects.ProjectCollectionStatus[0 /* SUCCESS */]).up().ele("code", projects.ProjectCollectionError[0 /* OK */]).up().ele("storeDirectory", this._projects.storeDirectory).up().ele("userDirectory", this._projects.userDirectory).up().ele("project", { id: prj.id }).ele("projectDirectory", prj.directory).up();
            if (bld) {
                // convert enum array to string array and generate a enum1,emum2... string
                var stateHistory = bld.history.map(function (e) {
                    return build.BuildState[e];
                }).reduce(function (prev, curr) {
                    return prev + "," + curr;
                });
                project.ele("configuration", { id: bld.id }).ele("outputDirectory", bld.outputDirectory).up().ele("logFileName", bld.logFileName).up().ele("name", bld.config.config).up().ele("arch", bld.config.arch).up().ele("sdk", bld.config.sdk).up().ele("build").ele("state", build.BuildState[bld.state]).up().ele("result", build.BuildResult[bld.result]).up().ele("stateHistory", stateHistory).up().up();
            }
            res.write(project.end({ pretty: true }));
            res.end();
        };
        return VCLanguageSpecificsResponse;
    })();
    VCRemoteLib.VCLanguageSpecificsResponse = VCLanguageSpecificsResponse;
})(VCRemoteLib || (VCRemoteLib = {}));

module.exports = VCRemoteLib;
