const UserError = require('vn-loopback/util/user-error');
const fs = require('fs-extra');
const path = require('path');

module.exports = Self => {
    Self.remoteMethodCtx('download', {
        description: 'Get the user image',
        accessType: 'READ',
        accepts: [
            {
                arg: 'collection',
                type: 'String',
                description: 'The image collection',
                http: {source: 'path'}
            },
            {
                arg: 'size',
                type: 'String',
                description: 'The image size',
                http: {source: 'path'}
            },
            {
                arg: 'id',
                type: 'Number',
                description: 'The user id',
                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: `/:collection/:size/:id/download`,
            verb: 'GET'
        }
    });

    Self.download = async function(ctx, collection, size, id) {
        const models = Self.app.models;
        const filter = {where: {name: collection}};
        const imageCollection = await models.ImageCollection.findOne(filter);
        const entity = await models[imageCollection.model].findById(id, {
            fields: ['id', imageCollection.property]
        });

        if (!entity) return false;

        const image = await models.Image.findOne({where: {
            collectionFk: collection,
            name: entity[imageCollection.property]}
        });

        if (!image) return false;

        const hasReadRole = models.ImageCollection.hasReadRole(ctx, collection);
        if (!hasReadRole)
            throw new UserError(`You don't have enough privileges`);

        const container = await models.ImageContainer.getContainer(collection);
        const rootPath = container.client.root;
        const fileSrc = path.join(rootPath, collection, size);
        const file = {
            path: `${fileSrc}/${image.name}.png`,
            contentType: 'image/png',
            name: `${image.name}.png`
        };

        if (!fs.existsSync(file.path)) return [];

        await fs.access(file.path);
        const stream = fs.createReadStream(file.path);
        return [stream, file.contentType, `filename="${file.name}"`];
    };
};