/* eslint max-len: ["error", { "code": 180 }]*/
const axios = require('axios');
const UserError = require('vn-loopback/util/user-error');

module.exports = Self => {
    Self.remoteMethodCtx('download', {
        description: 'Download an docuware PDF',
        accessType: 'READ',
        accepts: [
            {
                arg: 'id',
                type: 'number',
                description: 'The ticket id',
                http: {source: 'path'}
            },
            {
                arg: 'fileCabinet',
                type: 'string',
                description: 'The file cabinet',
                http: {source: 'path'}
            }
        ],
        returns: [
            {
                arg: 'body',
                type: 'file',
                root: true
            }, {
                arg: 'Content-Type',
                type: 'string',
                http: {target: 'header'}
            }, {
                arg: 'Content-Disposition',
                type: 'string',
                http: {target: 'header'}
            }
        ],
        http: {
            path: `/:id/download/:fileCabinet`,
            verb: 'GET'
        }
    });

    Self.download = async function(ctx, id, fileCabinet) {
        const models = Self.app.models;
        const docuwareFile = await models.Docuware.checkFile(ctx, id, fileCabinet, true);
        if (!docuwareFile) throw new UserError('The DOCUWARE PDF document does not exists');

        const fileCabinetId = await Self.getFileCabinet(fileCabinet);
        const options = await Self.getOptions();
        options.headers.responseType = 'stream';

        const fileName = `filename="${id}.pdf"`;
        const contentType = 'application/pdf';
        const downloadUri = `${options.url}/FileCabinets/${fileCabinetId}/Documents/${docuwareFile.id}/FileDownload?targetFileType=Auto&keepAnnotations=false`;

        const stream = await axios.get(downloadUri, options.headers);

        return [stream.data, contentType, fileName];
    };
};