import superagent from 'superagent'

import VaultService from './vault-service.js';

export default class AutoresponderService {

    constructor(config) {
        this.request = superagent;
        this.config = config;
    }

    async runScenario(data) {

        if (this.config.autoresponderConfig &&
            !this.config.autoresponderConfig.token &&
            this.config.autoresponderConfig.vaultConfig &&
            this.config.autoresponderConfig.vaultConfig.path &&
            this.config.autoresponderConfig.vaultConfig.key) {
            if (!this.vault) {
                if (!this.config.vaultConfig) {
                    throw new Error('Missing config.vaultConfig');
                }
                this.vault = new VaultService(this.config);
            }
            await this.vault.getSecret(this.config.autoresponderConfig.vaultConfig.path, this.config.autoresponderConfig.vaultConfig.key).then(value => {
                if (value[this.config.autoresponderConfig.vaultConfig.key]) {
                    Object.keys(value[this.config.autoresponderConfig.vaultConfig.key]).forEach(varKey => {
                        if (!this.config.autoresponderConfig[varKey]) {
                            this.config.autoresponderConfig[varKey] = value[this.config.autoresponderConfig.vaultConfig.key][varKey]
                        }
                    })
                }
            })
        }

        data["candidateUsers"] = this.config.autoresponderConfig.candidateUsers;
        try {
            let response = false;
            if (this.config.autoresponderConfig.token) {
                response = await this.request
                    .post(this.config.autoresponderConfig.baseUrl + this.config.autoresponderConfig.scenarioDir + "/run?folder=" + this.config.autoresponderConfig.scenarioSubDir)
                    .type('json')
                    .set('Authorization', this.config.autoresponderConfig.token)
                    .send(data);
            } else {
                response = await this.request
                    .post(this.config.autoresponderConfig.baseUrl + this.config.autoresponderConfig.scenarioDir + "/run?folder=" + this.config.autoresponderConfig.scenarioSubDir)
                    .type('json')
                    .send(data);
            }
            if (response) {
                if (!response.body.result) {
                    let failedScenarios = [];
                    Object.keys(response.body.scenarios).forEach(scenario => {
                        if (!response.body.scenarios[scenario]) {
                            failedScenarios.push(scenario);
                        }
                    });
                    throw new Error('Failed scenario(s): ' + failedScenarios.join(', '));
                }
            } else {
                throw new Error('Response is ' + response);
            }
        } catch (error) {
            throw new Error('Error running autoresponder: ' + error)
        }

    }
}
