const axios = require('axios');

module.exports = Self => {
    /**
     * Returns the dialog id
     *
     * @param {string} code - The fileCabinet name
     * @param {string} action - The fileCabinet name
     * @param {string} fileCabinetId - Optional The fileCabinet name
     * @return {number} - The fileCabinet id
     */
    Self.getDialog = async(code, action, fileCabinetId) => {
        const docuwareInfo = await Self.app.models.Docuware.findOne({
            where: {
                code: code,
                action: action
            }
        });
        if (!fileCabinetId) fileCabinetId = await Self.getFileCabinet(code);

        const options = await Self.getOptions();

        if (!process.env.NODE_ENV)
            return Math.round();

        const response = await axios.get(`${options.url}/FileCabinets/${fileCabinetId}/dialogs`, options.headers);
        const dialogs = response.data.Dialog;
        const dialogId = dialogs.find(dialogs => dialogs.DisplayName === docuwareInfo.dialogName).Id;

        return dialogId;
    };

    /**
     * Returns the fileCabinetId
     *
     * @param {string} code - The fileCabinet code
     * @return {number} - The fileCabinet id
     */
    Self.getFileCabinet = async code => {
        const options = await Self.getOptions();
        const docuwareInfo = await Self.app.models.Docuware.findOne({
            where: {
                code: code
            }
        });

        if (!process.env.NODE_ENV)
            return Math.round();

        const fileCabinetResponse = await axios.get(`${options.url}/FileCabinets`, options.headers);
        const fileCabinets = fileCabinetResponse.data.FileCabinet;
        const fileCabinetId = fileCabinets.find(fileCabinet => fileCabinet.Name === docuwareInfo.fileCabinetName).Id;

        return fileCabinetId;
    };

    /**
     * Returns basic headers
     *
     * @param {string} cookie - The docuware cookie
     * @return {object} - The headers
     */
    Self.getOptions = async() => {
        const docuwareConfig = await Self.app.models.DocuwareConfig.findOne();
        const headers = {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Cookie': docuwareConfig.cookie
            }
        };

        return {
            url: docuwareConfig.url,
            headers
        };
    };
};