/*****************************************************************************\
|                                               ( )_  _                       |
|    _ _    _ __   _ _    __    ___ ___     _ _ | ,_)(_)  ___   ___     _     |
|   ( '_`\ ( '__)/'_` ) /'_ `\/' _ ` _ `\ /'_` )| |  | |/',__)/' v `\ /'_`\   |
|   | (_) )| |  ( (_| |( (_) || ( ) ( ) |( (_| || |_ | |\__, \| (˅) |( (_) )  |
|   | ,__/'(_)  `\__,_)`\__  |(_) (_) (_)`\__,_)`\__)(_)(____/(_) (_)`\___/'  |
|   | |                ( )_) |                                                |
|   (_)                 \___/'                                                |
|                                                                             |
| General Bots Copyright (c) Pragmatismo.io. All rights reserved.             |
| Licensed under the AGPL-3.0.                                                |
|                                                                             |
| According to our dual licensing model, this program can be used either      |
| under the terms of the GNU Affero General Public License, version 3,        |
| or under a proprietary license.                                             |
|                                                                             |
| The texts of the GNU Affero General Public License with an additional       |
| permission and of our proprietary license can be found at and               |
| in the LICENSE file you have received along with this program.              |
|                                                                             |
| This program is distributed in the hope that it will be useful,             |
| but WITHOUT ANY WARRANTY, without even the implied warranty of              |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the                |
| GNU Affero General Public License for more details.                         |
|                                                                             |
| "General Bots" is a registered trademark of Pragmatismo.io.                 |
| The licensing of the program under the AGPLv3 does not imply a              |
| trademark license. Therefore any rights, title and interest in              |
| our trademarks remain entirely with us.                                     |
|                                                                             |
\*****************************************************************************/
/**
 * @fileoverview General Bots server core.
 */
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureDeployerService = void 0;
const ms_rest_js_1 = require("@azure/ms-rest-js");
const azure_arm_cognitiveservices_1 = require("azure-arm-cognitiveservices");
const azure_arm_resource_1 = require("azure-arm-resource");
const azure_arm_search_1 = require("azure-arm-search");
const azure_arm_sql_1 = require("azure-arm-sql");
const azure_arm_website_1 = require("azure-arm-website");
const botlib_1 = require("botlib");
const GBAdminService_1 = require("../../../packages/admin.gbapp/services/GBAdminService");
const core_gbapp_1 = require("../../../packages/core.gbapp");
const GBConfigService_1 = require("../../../packages/core.gbapp/services/GBConfigService");
const MicrosoftGraph = require("@microsoft/microsoft-graph-client");
const Spinner = require('cli-spinner').Spinner;
// tslint:disable-next-line: no-submodule-imports
const simplegit = require("simple-git/promise");
const git = simplegit();
const urlJoin = require("url-join");
const iconUrl = 'https://github.com/pragmatismo-io/BotServer/blob/master/docs/images/generalbots-logo-squared.png';
const publicIp = require('public-ip');
const WebSiteResponseTimeout = 900;
/**
 * Deployer for Microsoft cloud.
 */
class AzureDeployerService {
    constructor(deployer, freeTier = true) {
        this.apiVersion = '2017-12-01';
        this.defaultEndPoint = 'http://localhost:4242';
        this.provider = 'Microsoft.BotService';
        this.deployer = deployer;
        this.freeTier = freeTier;
    }
    async runSearch(instance) {
        await this.deployer.rebuildIndex(instance, this.getKBSearchSchema(instance.searchIndex));
    }
    static async createInstance(deployer) {
        const username = GBConfigService_1.GBConfigService.get('CLOUD_USERNAME');
        const password = GBConfigService_1.GBConfigService.get('CLOUD_PASSWORD');
        const credentials = await GBAdminService_1.GBAdminService.getADALCredentialsFromUsername(username, password);
        const subscriptionId = GBConfigService_1.GBConfigService.get('CLOUD_SUBSCRIPTIONID');
        const service = new AzureDeployerService(deployer);
        service.core = deployer.core;
        service.initServices(credentials, subscriptionId);
        return service;
    }
    static createRequestObject(url, accessToken, verb, body) {
        const req = new ms_rest_js_1.WebResource();
        req.method = verb;
        req.url = url;
        req.headers.set('Content-Type', 'application/json');
        req.headers.set('accept-language', '*');
        req.headers.set('Authorization', `Bearer ${accessToken}`);
        req.body = body;
        return req;
    }
    async getSubscriptions(credentials) {
        const subscriptionClient = new azure_arm_resource_1.SubscriptionClient.default(credentials);
        return subscriptionClient.subscriptions.list();
    }
    getKBSearchSchema(indexName) {
        return {
            name: indexName,
            fields: [
                {
                    name: 'questionId',
                    type: 'Edm.String',
                    searchable: false,
                    filterable: false,
                    retrievable: true,
                    sortable: false,
                    facetable: false,
                    key: true
                },
                {
                    name: 'subject1',
                    type: 'Edm.String',
                    searchable: true,
                    filterable: false,
                    retrievable: false,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'subject2',
                    type: 'Edm.String',
                    searchable: true,
                    filterable: false,
                    retrievable: false,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'subject3',
                    type: 'Edm.String',
                    searchable: true,
                    filterable: false,
                    retrievable: false,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'subject4',
                    type: 'Edm.String',
                    searchable: true,
                    filterable: false,
                    retrievable: false,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'content',
                    type: 'Edm.String',
                    searchable: true,
                    filterable: false,
                    retrievable: false,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'answerId',
                    type: 'Edm.Int32',
                    searchable: false,
                    filterable: false,
                    retrievable: true,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'instanceId',
                    type: 'Edm.Int32',
                    searchable: false,
                    filterable: true,
                    retrievable: true,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'skipIndex',
                    type: 'Edm.Boolean',
                    searchable: false,
                    filterable: true,
                    retrievable: true,
                    sortable: false,
                    facetable: false,
                    key: false
                },
                {
                    name: 'packageId',
                    type: 'Edm.Int32',
                    searchable: false,
                    filterable: true,
                    retrievable: true,
                    sortable: false,
                    facetable: false,
                    key: false
                }
            ],
            scoringProfiles: [],
            defaultScoringProfile: undefined,
            corsOptions: undefined
        };
    }
    async botExists(botId) {
        const baseUrl = `https://management.azure.com/`;
        const username = GBConfigService_1.GBConfigService.get('CLOUD_USERNAME');
        const password = GBConfigService_1.GBConfigService.get('CLOUD_PASSWORD');
        const accessToken = await GBAdminService_1.GBAdminService.getADALTokenFromUsername(username, password);
        const httpClient = new ms_rest_js_1.ServiceClient();
        const query = `providers/${this.provider}/checkNameAvailability/Action?api-version=${this.apiVersion}`;
        const url = urlJoin(baseUrl, query);
        const body = {
            name: botId,
            type: "botServices"
        };
        const req = AzureDeployerService.createRequestObject(url, accessToken, 'POST', JSON.stringify(body));
        const res = await httpClient.sendRequest(req);
        return !res.parsedBody.valid;
    }
    async updateBotProxy(botId, group, endpoint) {
        const baseUrl = `https://management.azure.com/`;
        const username = GBConfigService_1.GBConfigService.get('CLOUD_USERNAME');
        const password = GBConfigService_1.GBConfigService.get('CLOUD_PASSWORD');
        const subscriptionId = GBConfigService_1.GBConfigService.get('CLOUD_SUBSCRIPTIONID');
        const accessToken = await GBAdminService_1.GBAdminService.getADALTokenFromUsername(username, password);
        const httpClient = new ms_rest_js_1.ServiceClient();
        const parameters = {
            properties: {
                endpoint: endpoint
            }
        };
        const query = `subscriptions/${subscriptionId}/resourceGroups/${group}/providers/${this.provider}/botServices/${botId}?api-version=${this.apiVersion}`;
        const url = urlJoin(baseUrl, query);
        const req = AzureDeployerService.createRequestObject(url, accessToken, 'PATCH', JSON.stringify(parameters));
        const res = await httpClient.sendRequest(req);
        // CHECK
        if (!JSON.parse(res.bodyAsText).id) {
            throw res.bodyAsText;
        }
        botlib_1.GBLog.info(`Bot proxy updated at: ${endpoint}.`);
    }
    async updateBot(botId, group, name, description, endpoint) {
        const baseUrl = `https://management.azure.com/`;
        const username = GBConfigService_1.GBConfigService.get('CLOUD_USERNAME');
        const password = GBConfigService_1.GBConfigService.get('CLOUD_PASSWORD');
        const subscriptionId = GBConfigService_1.GBConfigService.get('CLOUD_SUBSCRIPTIONID');
        const accessToken = await GBAdminService_1.GBAdminService.getADALTokenFromUsername(username, password);
        const httpClient = new ms_rest_js_1.ServiceClient();
        const parameters = {
            properties: {
                description: `${description}`,
                displayName: name,
                endpoint: endpoint,
                iconUrl: iconUrl
            }
        };
        const query = `subscriptions/${subscriptionId}/resourceGroups/${group}/providers/${this.provider}/botServices/${botId}?api-version=${this.apiVersion}`;
        const url = urlJoin(baseUrl, query);
        const req = AzureDeployerService.createRequestObject(url, accessToken, 'PATCH', JSON.stringify(parameters));
        const res = await httpClient.sendRequest(req);
        // CHECK
        if (!JSON.parse(res.bodyAsText).id) {
            throw res.bodyAsText;
        }
        botlib_1.GBLog.info(`Bot updated at: ${endpoint}.`);
    }
    async deleteBot(botId, group) {
        const baseUrl = `https://management.azure.com/`;
        const username = GBConfigService_1.GBConfigService.get('CLOUD_USERNAME');
        const password = GBConfigService_1.GBConfigService.get('CLOUD_PASSWORD');
        const subscriptionId = GBConfigService_1.GBConfigService.get('CLOUD_SUBSCRIPTIONID');
        const accessToken = await GBAdminService_1.GBAdminService.getADALTokenFromUsername(username, password);
        const httpClient = new ms_rest_js_1.ServiceClient();
        const query = `subscriptions/${subscriptionId}/resourceGroups/${group}/providers/${this.provider}/botServices/${botId}?api-version=${this.apiVersion}`;
        const url = urlJoin(baseUrl, query);
        const req = AzureDeployerService.createRequestObject(url, accessToken, 'DELETE', undefined);
        const res = await httpClient.sendRequest(req);
        if (res.bodyAsText !== "") {
            throw res.bodyAsText;
        }
        botlib_1.GBLog.info(`Bot ${botId} was deleted from the provider.`);
    }
    async openStorageFirewall(groupName, serverName) {
        const username = GBConfigService_1.GBConfigService.get('CLOUD_USERNAME');
        const password = GBConfigService_1.GBConfigService.get('CLOUD_PASSWORD');
        const subscriptionId = GBConfigService_1.GBConfigService.get('CLOUD_SUBSCRIPTIONID');
        const credentials = await GBAdminService_1.GBAdminService.getADALCredentialsFromUsername(username, password);
        const storageClient = new azure_arm_sql_1.SqlManagementClient(credentials, subscriptionId);
        const ip = await publicIp.v4();
        let params = {
            startIpAddress: ip,
            endIpAddress: ip
        };
        await storageClient.firewallRules.createOrUpdate(groupName, serverName, 'gb', params);
    }
    async deployFarm(proxyAddress, instance, credentials, subscriptionId) {
        const culture = 'en-us';
        this.initServices(credentials, subscriptionId);
        const spinner = new Spinner('%s');
        spinner.start();
        spinner.setSpinnerString('|/-\\');
        let keys;
        const name = instance.botId;
        botlib_1.GBLog.info(`Deploying Deploy Group (It may take a few minutes)...`);
        await this.createDeployGroup(name, instance.cloudLocation);
        botlib_1.GBLog.info(`Deploying Bot Server...`);
        const serverFarm = await this.createHostingPlan(name, `${name}-server-plan`, instance.cloudLocation);
        const serverName = `${name}-server`;
        await this.createServer(serverFarm.id, name, serverName, instance.cloudLocation);
        botlib_1.GBLog.info(`Deploying Bot Storage...`);
        const administratorLogin = `sa${GBAdminService_1.GBAdminService.getRndReadableIdentifier()}`;
        const administratorPassword = GBAdminService_1.GBAdminService.getRndPassword();
        const storageServer = `${name.toLowerCase()}-storage-server`;
        const storageName = `${name}-storage`;
        await this.createStorageServer(name, storageServer, administratorLogin, administratorPassword, storageServer, instance.cloudLocation);
        await this.createStorage(name, storageServer, storageName, instance.cloudLocation);
        instance.storageUsername = administratorLogin;
        instance.storagePassword = administratorPassword;
        instance.storageName = storageName;
        instance.storageDialect = 'mssql';
        instance.storageServer = `${storageServer}.database.windows.net`;
        botlib_1.GBLog.info(`Deploying Search...`);
        const searchName = `${name}-search`.toLowerCase();
        await this.createSearch(name, searchName, instance.cloudLocation);
        const searchKeys = await this.searchClient.adminKeys.get(name, searchName);
        instance.searchHost = `${searchName}.search.windows.net`;
        instance.searchIndex = 'azuresql-index';
        instance.searchIndexer = 'azuresql-indexer';
        instance.searchKey = searchKeys.primaryKey;
        botlib_1.GBLog.info(`Deploying Speech...`);
        const speech = await this.createSpeech(name, `${name}-speech`, instance.cloudLocation);
        keys = await this.cognitiveClient.accounts.listKeys(name, speech.name);
        instance.speechEndpoint = speech.endpoint;
        instance.speechKey = keys.key1;
        botlib_1.GBLog.info(`Deploying Text Analytics...`);
        const textAnalytics = await this.createTextAnalytics(name, `${name}-textanalytics`, instance.cloudLocation);
        keys = await this.cognitiveClient.accounts.listKeys(name, textAnalytics.name);
        instance.textAnalyticsEndpoint = textAnalytics.endpoint.replace(`/text/analytics/v2.0`, '');
        instance.textAnalyticsKey = keys.key1;
        botlib_1.GBLog.info(`Deploying SpellChecker...`);
        const spellChecker = await this.createSpellChecker(name, `${name}-spellchecker`);
        keys = await this.cognitiveClient.accounts.listKeys(name, spellChecker.name);
        instance.spellcheckerKey = keys.key1;
        instance.spellcheckerEndpoint = spellChecker.endpoint;
        botlib_1.GBLog.info(`Deploying NLP...`);
        const nlp = await this.createNLP(name, `${name}-nlp`, instance.cloudLocation);
        const nlpa = await this.createNLPAuthoring(name, `${name}-nlpa`, instance.cloudLocation);
        keys = await this.cognitiveClient.accounts.listKeys(name, nlp.name);
        let authoringKeys = await this.cognitiveClient.accounts.listKeys(name, nlpa.name);
        instance.nlpAuthoringKey = authoringKeys.key1;
        const nlpAppId = await this.createNLPService(name, name, instance.cloudLocation, culture, instance.nlpAuthoringKey);
        instance.nlpEndpoint = nlp.endpoint;
        instance.nlpKey = keys.key1;
        instance.nlpAppId = nlpAppId;
        botlib_1.GBLog.info(`Deploying Bot...`);
        instance.botEndpoint = this.defaultEndPoint;
        instance = await this.internalDeployBot(instance, this.accessToken, name, name, name, 'General BootBot', `${proxyAddress}/api/messages/${name}`, 'global', instance.nlpAppId, instance.nlpKey, instance.marketplaceId, instance.marketplacePassword, instance.cloudSubscriptionId);
        botlib_1.GBLog.info('Updating server environment variables...');
        await this.updateWebisteConfig(name, serverName, serverFarm.id, instance);
        spinner.stop();
        botlib_1.GBLog.info('Opening your browser with default.gbui...');
        const opn = require('opn');
        opn(`http://localhost:4242`);
        return instance;
    }
    async deployToCloud(title, username, password, cloudLocation, authoringKey, appId, appPassword, subscriptionId) {
        const instance = {};
        instance.state = 'active';
        instance.botId = title;
        instance.cloudUsername = username;
        instance.cloudPassword = password;
        instance.cloudSubscriptionId = subscriptionId;
        instance.cloudLocation = cloudLocation;
        instance.nlpAuthoringKey = authoringKey;
        instance.marketplaceId = appId;
        instance.marketplacePassword = appPassword;
        instance.adminPass = GBAdminService_1.GBAdminService.getRndPassword();
        const credentials = await GBAdminService_1.GBAdminService.getADALCredentialsFromUsername(username, password);
        // tslint:disable-next-line:no-http-string
        const url = `https://${instance.botId}.azurewebsites.net`;
        this.deployFarm(url, instance, credentials, subscriptionId);
    }
    /**
     * @see https://github.com/Azure/azure-rest-api-specs/blob/master/specification/botservice/resource-manager/Microsoft.BotService/preview/2017-12-01/botservice.json
     */
    async internalDeployBot(instance, accessToken, botId, name, group, description, endpoint, location, nlpAppId, nlpKey, appId, appPassword, subscriptionId) {
        return new Promise(async (resolve, reject) => {
            const baseUrl = `https://management.azure.com/`;
            await this.registerProviders(subscriptionId, baseUrl, accessToken);
            instance.marketplaceId = appId;
            instance.marketplacePassword = appPassword;
            instance.engineName = core_gbapp_1.GBCorePackage['CurrentEngineName'];
            const parameters = {
                location: location,
                sku: {
                    name: this.freeTier ? 'F0' : 'S1'
                },
                name: botId,
                kind: 'bot',
                properties: {
                    description: description,
                    displayName: name,
                    endpoint: endpoint,
                    iconUrl: iconUrl,
                    luisAppIds: [nlpAppId],
                    luisKey: nlpKey,
                    msaAppId: appId,
                    msaAppPassword: appPassword,
                    enabledChannels: ['webchat', "skype"],
                    configuredChannels: ['webchat', "skype"] //, "facebook"]
                }
            };
            const httpClient = new ms_rest_js_1.ServiceClient();
            let query = `subscriptions/${subscriptionId}/resourceGroups/${group}/providers/${this.provider}/botServices/${botId}?api-version=${this.apiVersion}`;
            let url = urlJoin(baseUrl, query);
            let req = AzureDeployerService.createRequestObject(url, accessToken, 'PUT', JSON.stringify(parameters));
            const res = await httpClient.sendRequest(req);
            if (!JSON.parse(res.bodyAsText).id) {
                reject(res.bodyAsText);
                return;
            }
            try {
                //tslint:disable-next-line:max-line-length
                query = `subscriptions/${subscriptionId}/resourceGroups/${group}/providers/Microsoft.BotService/botServices/${botId}/channels/WebChatChannel/listChannelWithKeys?api-version=${this.apiVersion}`;
                url = urlJoin(baseUrl, query);
                req = AzureDeployerService.createRequestObject(url, accessToken, 'POST', JSON.stringify(parameters));
                const resChannel = await httpClient.sendRequest(req);
                const key = JSON.parse(resChannel.bodyAsText).properties.properties.sites[0].key;
                instance.webchatKey = key;
                instance.whatsappBotKey = key;
                resolve(instance);
            }
            catch (error) {
                reject(error);
            }
        });
    }
    async syncBotServerRepository(group, name) {
        await this.webSiteClient.webApps.syncRepository(group, name);
    }
    initServices(credentials, subscriptionId) {
        this.resourceClient = new azure_arm_resource_1.ResourceManagementClient.default(credentials, subscriptionId);
        this.webSiteClient = new azure_arm_website_1.WebSiteManagementClient(credentials, subscriptionId);
        this.storageClient = new azure_arm_sql_1.SqlManagementClient(credentials, subscriptionId);
        this.cognitiveClient = new azure_arm_cognitiveservices_1.CognitiveServicesManagementClient(credentials, subscriptionId);
        this.searchClient = new azure_arm_search_1.SearchManagementClient(credentials, subscriptionId);
        this.accessToken = credentials.tokenCache._entries[0].accessToken;
    }
    async createStorageServer(group, name, administratorLogin, administratorPassword, serverName, location) {
        const params = {
            location: location,
            administratorLogin: administratorLogin,
            administratorLoginPassword: administratorPassword,
            fullyQualifiedDomainName: serverName
        };
        const database = await this.storageClient.servers.createOrUpdate(group, name, params);
        // AllowAllWindowsAzureIps must be created that way, so the Azure Search can 
        // access SQL Database to index its contents.
        const paramsFirewall = {
            startIpAddress: '0.0.0.0',
            endIpAddress: '0.0.0.0'
        };
        await this.storageClient.firewallRules.createOrUpdate(group, name, 'AllowAllWindowsAzureIps', paramsFirewall);
        return database;
    }
    async createApplication(token, name) {
        return new Promise((resolve, reject) => {
            let client = MicrosoftGraph.Client.init({
                authProvider: done => {
                    done(null, token);
                }
            });
            const app = {
                displayName: name
            };
            client.api(`/applications`).post(app, (err, res) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(res);
                }
            });
        });
    }
    async createApplicationSecret(token, appId) {
        return new Promise((resolve, reject) => {
            let client = MicrosoftGraph.Client.init({
                authProvider: done => {
                    done(null, token);
                }
            });
            const body = {
                passwordCredential: {
                    displayName: "General Bots Generated"
                }
            };
            client.api(`/applications/${appId}/addPassword`).post(body, (err, res) => {
                if (err) {
                    reject(err);
                }
                else {
                    resolve(res.secretText);
                }
            });
        });
    }
    async registerProviders(subscriptionId, baseUrl, accessToken) {
        const query = `subscriptions/${subscriptionId}/providers/${this.provider}/register?api-version=2018-02-01`;
        const requestUrl = urlJoin(baseUrl, query);
        const req = new ms_rest_js_1.WebResource();
        req.method = 'POST';
        req.url = requestUrl;
        req.headers = {};
        req.headers['Content-Type'] = 'application/json; charset=utf-8';
        req.headers['accept-language'] = '*';
        req.headers.Authorization = `Bearer ${accessToken}`;
    }
    async createNLPService(name, description, location, culture, authoringKey) {
        const parameters = {
            name: name,
            description: description,
            culture: culture
        };
        const body = JSON.stringify(parameters);
        const apps = await this.makeNlpRequest(location, authoringKey, undefined, 'GET', 'apps');
        let app = null;
        if (apps.bodyAsText && apps.bodyAsText !== '[]') {
            const result = JSON.parse(apps.bodyAsText);
            if (result.error) {
                if (result.error.code !== "401") {
                    throw new Error(result.error);
                }
            }
            else {
                app = result.filter(x => x.name === name)[0];
            }
        }
        let id;
        if (!app) {
            const res = await this.makeNlpRequest(location, authoringKey, body, 'POST', 'apps');
            id = res.bodyAsText;
        }
        else {
            id = app.id;
        }
        return id.replace(/\'/gi, '');
    }
    async makeNlpRequest(location, authoringKey, body, method, resource) {
        const req = new ms_rest_js_1.WebResource();
        req.method = method;
        req.url = `https://${location}.api.cognitive.microsoft.com/luis/api/v2.0/${resource}`;
        req.headers.set('Content-Type', 'application/json');
        req.headers.set('accept-language', '*');
        req.headers.set('Ocp-Apim-Subscription-Key', authoringKey);
        req.body = body;
        const httpClient = new ms_rest_js_1.ServiceClient();
        return await httpClient.sendRequest(req);
    }
    async refreshEntityList(location, nlpAppId, clEntityId, nlpKey, data) {
        const req = new ms_rest_js_1.WebResource();
        req.method = 'PUT';
        req.url = `https://${location}.api.cognitive.microsoft.com/luis/api/v2.0/apps/${nlpAppId}/versions/0.1/closedlists/${clEntityId}`;
        req.headers.set('Content-Type', 'application/json');
        req.headers.set('accept-language', '*');
        req.headers.set('Ocp-Apim-Subscription-Key', nlpKey);
        req.body = JSON.stringify(data);
        const httpClient = new ms_rest_js_1.ServiceClient();
        return await httpClient.sendRequest(req);
    }
    async trainNLP(location, nlpAppId, nlpAuthoringKey) {
        const req = new ms_rest_js_1.WebResource();
        req.method = 'POST';
        req.url = `https://${location}.api.cognitive.microsoft.com/luis/api/v2.0/apps/${nlpAppId}/versions/0.1/train`;
        req.headers.set('Content-Type', 'application/json');
        req.headers.set('accept-language', '*');
        req.headers.set('Ocp-Apim-Subscription-Key', nlpAuthoringKey);
        const httpClient = new ms_rest_js_1.ServiceClient();
        return await httpClient.sendRequest(req);
    }
    async publishNLP(location, nlpAppId, nlpAuthoringKey) {
        const body = {
            versionId: "0.1",
            isStaging: false,
            directVersionPublish: false
        };
        const req = new ms_rest_js_1.WebResource();
        req.method = 'POST';
        req.url = `https://${location}.api.cognitive.microsoft.com/luis/api/v2.0/apps/${nlpAppId}/publish`;
        req.headers.set('Content-Type', 'application/json');
        req.headers.set('accept-language', '*');
        req.headers.set('Ocp-Apim-Subscription-Key', nlpAuthoringKey);
        req.body = JSON.stringify(body);
        const httpClient = new ms_rest_js_1.ServiceClient();
        return await httpClient.sendRequest(req);
    }
    async createSearch(group, name, location) {
        const params = {
            sku: {
                name: this.freeTier ? 'free' : 'standard'
            },
            location: location
        };
        return await this.searchClient.services.createOrUpdate(group, name, params);
    }
    async createStorage(group, serverName, name, location) {
        const params = {
            sku: { name: this.freeTier ? 'Free' : 'Basic' },
            createMode: 'Default',
            location: location
        };
        return await this.storageClient.databases.createOrUpdate(group, serverName, name, params);
    }
    async createCognitiveServices(group, name, location, kind) {
        const params = {
            sku: {
                name: ""
            },
            createMode: 'Default',
            location: location,
            kind: kind,
            properties: {}
        };
        if (kind === 'LUIS.Authoring') {
            params.sku.name = this.freeTier ? 'F0' : 'S0';
        }
        else if (kind === 'TextAnalytics') {
            params.sku.name = this.freeTier ? 'F0' : 'S0';
        }
        else if (kind === 'Bing.SpellCheck.v7') {
            params.sku.name = this.freeTier ? 'S0' : 'S1';
        }
        else if (kind === 'CognitiveServices') {
            params.sku.name = 'S0';
        }
        return await this.cognitiveClient.accounts.create(group, name, params);
    }
    async createSpeech(group, name, location) {
        return await this.createCognitiveServices(group, name, location, 'SpeechServices');
    }
    async createNLP(group, name, location) {
        return await this.createCognitiveServices(group, name, location, 'LUIS');
    }
    async createNLPAuthoring(group, name, location) {
        return await this.createCognitiveServices(group, name, location, 'LUIS.Authoring');
    }
    async createSpellChecker(group, name) {
        return await this.createCognitiveServices(group, name, 'westus', 'CognitiveServices');
    }
    async createTextAnalytics(group, name, location) {
        return await this.createCognitiveServices(group, name, location, 'TextAnalytics');
    }
    async createDeployGroup(name, location) {
        const params = { location: location };
        return await this.resourceClient.resourceGroups.createOrUpdate(name, params);
    }
    async createHostingPlan(group, name, location) {
        const params = {
            serverFarmWithRichSkuName: name,
            location: location,
            sku: {
                name: this.freeTier ? 'F1' : 'S1',
                capacity: 1,
                tier: this.freeTier ? 'Free' : 'Standard'
            }
        };
        return await this.webSiteClient.appServicePlans.createOrUpdate(group, name, params);
    }
    async createServer(farmId, group, name, location) {
        let tryed = false;
        const create = async () => {
            const parameters = {
                location: location,
                serverFarmId: farmId,
                siteConfig: {
                    nodeVersion: GBAdminService_1.GBAdminService.getNodeVersion(),
                    detailedErrorLoggingEnabled: true,
                    requestTracingEnabled: true
                }
            };
            const server = await this.webSiteClient.webApps.createOrUpdate(group, name, parameters);
            const siteLogsConfig = {
                applicationLogs: {
                    fileSystem: { level: 'Error' }
                }
            };
            await this.webSiteClient.webApps.updateDiagnosticLogsConfig(group, name, siteLogsConfig);
            const souceControlConfig = {
                repoUrl: 'https://github.com/GeneralBots/BotServer.git',
                branch: 'master',
                isManualIntegration: true,
                isMercurial: false,
                deploymentRollbackEnabled: false
            };
            await this.webSiteClient.webApps.createOrUpdateSourceControl(group, name, souceControlConfig);
            return server;
        };
        try {
            return await create();
        }
        catch (e) {
            if (!tryed) {
                tryed = true;
                botlib_1.GBLog.info('Retrying Deploying Bot Server...');
                try {
                    return await create();
                }
                catch (error) {
                    botlib_1.GBLog.info('Server creation failed at all on MSAzure, stopping...');
                    throw error;
                }
            }
        }
    }
    async updateWebisteConfig(group, name, serverFarmId, instance) {
        const parameters = {
            location: instance.cloudLocation,
            serverFarmId: serverFarmId,
            siteConfig: {
                appSettings: [
                    { name: 'WEBSITES_CONTAINER_START_TIME_LIMIT', value: `${WebSiteResponseTimeout}` },
                    { name: 'WEBSITE_NODE_DEFAULT_VERSION', value: GBAdminService_1.GBAdminService.getNodeVersion() },
                    { name: 'ADDITIONAL_DEPLOY_PATH', value: `` },
                    { name: 'ADMIN_PASS', value: `${instance.adminPass}` },
                    { name: 'BOT_ID', value: `${instance.botId}` },
                    { name: 'CLOUD_SUBSCRIPTIONID', value: `${instance.cloudSubscriptionId}` },
                    { name: 'CLOUD_LOCATION', value: `${instance.cloudLocation}` },
                    { name: 'CLOUD_GROUP', value: `${instance.botId}` },
                    { name: 'CLOUD_USERNAME', value: `${instance.cloudUsername}` },
                    { name: 'CLOUD_PASSWORD', value: `${instance.cloudPassword}` },
                    { name: 'MARKETPLACE_ID', value: `${instance.marketplaceId}` },
                    { name: 'MARKETPLACE_SECRET', value: `${instance.marketplacePassword}` },
                    { name: 'STORAGE_DIALECT', value: `${instance.storageDialect}` },
                    { name: 'STORAGE_SERVER', value: `${instance.storageServer}.database.windows.net` },
                    { name: 'STORAGE_NAME', value: `${instance.storageName}` },
                    { name: 'STORAGE_USERNAME', value: `${instance.storageUsername}` },
                    { name: 'STORAGE_PASSWORD', value: `${instance.storagePassword}` },
                    { name: 'STORAGE_SYNC', value: `true` }
                ]
            }
        };
        return await this.webSiteClient.webApps.createOrUpdate(group, name, parameters);
    }
}
exports.AzureDeployerService = AzureDeployerService;
//# sourceMappingURL=AzureDeployerService.js.map