import superagent from 'superagent'

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

export default class AutoresponderService {

    constructor(config, autoresponderScenario = 'autoresponderConfig', runPath = 'folder', waitForResult = true) {
        this.request = superagent;
        this.config = config;
        this.autoresponderScenario = autoresponderScenario;
        this.runPath = "/run?" + runPath + "=";
        this.waitForResult = waitForResult;
    }

    async runScenario(data) {
        if (this.config[this.autoresponderScenario] &&
            !this.config[this.autoresponderScenario].token &&
            this.config[this.autoresponderScenario].vaultConfig &&
            this.config[this.autoresponderScenario].vaultConfig.path &&
            this.config[this.autoresponderScenario].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[this.autoresponderScenario].vaultConfig.path, this.config[this.autoresponderScenario].vaultConfig.key).then(value => {
                if (value[this.config[this.autoresponderScenario].vaultConfig.key]) {
                    Object.keys(value[this.config[this.autoresponderScenario].vaultConfig.key]).forEach(varKey => {
                        if (!this.config[this.autoresponderScenario][varKey]) {
                            this.config[this.autoresponderScenario][varKey] = value[this.config[this.autoresponderScenario].vaultConfig.key][varKey]
                        }
                    })
                }
            })
        }
        try {
            let response = false;
            if (this.waitForResult) {
                response = await this.runPost(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);
                }
            }
            else this.runPost(data);
        } catch (error) {
            throw new Error('Error running autoresponder: ' + error)
        }

    }
    async runPost(data) {
        let response = false;
        let url = this.config[this.autoresponderScenario].baseUrl + this.config[this.autoresponderScenario].scenarioDir + this.runPath + this.config[this.autoresponderScenario].scenarioSubDir;
        // Only set candidateUsers if not provided in the data
        if (data) {
            if (!data.candidateUsers) {
                data["candidateUsers"] = this.config[this.autoresponderScenario].candidateUsers;
            }
        }
        if (this.config[this.autoresponderScenario].token) {
            if (data) {
                response = await this.request
                    .post(url)
                    .type('json')
                    .set('Authorization', this.config[this.autoresponderScenario].token)
                    .send(data);
            } else {
                response = await this.request
                    .post(url)
                    .set('Authorization', this.config[this.autoresponderScenario].token)
                    .send();
            }
        } else {
            response = await this.request
                .post(url)
                .type('json')
                .send(data);
        }
        return response;
    }
}
