const https = require('https');

module.exports = Self => {
    Self.remoteMethod('getVideo', {
        description: 'Get packing video',
        accessType: 'READ',
        accepts: [
            {
                arg: 'id',
                type: 'number',
                required: true,
                description: 'Ticket id'
            },
            {
                arg: 'filename',
                type: 'string',
                required: true,
                description: 'Time to add'
            },
            {
                arg: 'req',
                type: 'object',
                http: {source: 'req'}
            },
            {
                arg: 'res',
                type: 'object',
                http: {source: 'res'}
            }
        ],
        http: {
            path: `/getVideo`,
            verb: 'GET',
        },
    });

    Self.getVideo = async(id, filename, req, res, options) => {
        const models = Self.app.models;
        const myOptions = {};

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        const packingSiteConfig = await models.PackingSiteConfig.findOne({}, myOptions);

        const query = `
                SELECT
                    e.id,
                    ps.monitorId,
                    e.created
                FROM expedition e
                    JOIN host h ON Convert(h.code USING utf8mb3) COLLATE utf8mb3_unicode_ci = e.hostFk
                    JOIN packingSite ps ON  ps.hostFk = h.id
                WHERE e.id = ?;`;
        const [expedition] = await models.Expedition.rawSql(query, [id]);
        const monitorId = expedition.monitorId;

        const videoUrl =
            `/${packingSiteConfig.shinobiToken}/videos/${packingSiteConfig.shinobiGroupKey}/${monitorId}/${filename}`;

        const headers = Object.assign({}, req.headers, {
            host: 'shinobi.verdnatura.es'
        });
        const httpOptions = {
            host: 'shinobi.verdnatura.es',
            path: videoUrl,
            port: 443,
            headers
        };

        return new Promise((resolve, reject) => {
            const req = https.request(httpOptions, shinobiRes => {
                shinobiRes.pause();
                res.writeHeader(shinobiRes.statusCode, shinobiRes.headers);
                shinobiRes.pipe(res);
            });

            req.on('error', () => {
                reject();
            });

            req.on('end', () => {
                resolve();
            });
            req.end();
        });
    };
};