module.exports = Self => {
    Self.remoteMethod('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: 'filter',
                type: 'object',
                description: 'The filter'
            },
            {
                arg: 'signed',
                type: 'boolean',
                description: 'If pdf is necessary to be signed'
            },
        ],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/:id/checkFile`,
            verb: 'POST'
        }
    });

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

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

        if (!filter) {
            filter = {
                condition: [
                    {
                        DBName: docuwareInfo.findById,
                        Value: [id]
                    }
                ],
                sortOrder: [
                    {
                        Field: 'FILENAME',
                        Direction: 'Desc'
                    }
                ]
            };
        }
        if (signed) {
            filter.condition.push({
                DBName: 'ESTADO',
                Value: ['Firmado']
            });
        }

        try {
            const [response] = await Self.get(fileCabinet, filter);
            if (!response) return false;

            return {id: response['Document ID']};
        } catch (error) {
            return false;
        }
    };
};