const axios = require('axios');

module.exports = Self => {
    Self.remoteMethodCtx('checkFile', {
        description: 'Check if exist docuware file',
        accessType: 'READ',
        accepts: [
            {
                arg: 'id',
                type: 'number',
                description: 'The id',
                http: {source: 'path'}
            },
            {
                arg: 'fileCabinet',
                type: 'string',
                required: true,
                description: 'The fileCabinet name'
            },
            {
                arg: 'signed',
                type: 'boolean',
                required: true,
                description: 'If pdf is necessary to be signed'
            }
        ],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/:id/checkFile`,
            verb: 'POST'
        }
    });

    Self.checkFile = async function(ctx, id, fileCabinet, signed) {
        const models = Self.app.models;
        const action = 'find';

        const docuwareInfo = await models.Docuware.findOne({
            where: {
                code: fileCabinet,
                action: action
            }
        });

        const searchFilter = {
            condition: [
                {
                    DBName: docuwareInfo.findById,

                    Value: [id]
                }
            ],
            sortOrder: [
                {
                    Field: 'FILENAME',
                    Direction: 'Desc'
                }
            ]
        };

        try {
            const options = await Self.getOptions();

            const fileCabinetId = await Self.getFileCabinet(fileCabinet);
            const dialogId = await Self.getDialog(fileCabinet, action, fileCabinetId);

            const response = await axios.post(
                `${options.url}/FileCabinets/${fileCabinetId}/Query/DialogExpression?dialogId=${dialogId}`,
                searchFilter,
                options.headers
            );
            const [documents] = response.data.Items;
            if (!documents) return false;

            const state = documents.Fields.find(field => field.FieldName == 'ESTADO');
            if (signed && state.Item != 'Firmado') return false;

            return {id: documents.Id};
        } catch (error) {
            return false;
        }
    };
};