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

module.exports = Self => {
    require('../methods/dms/downloadFile')(Self);
    require('../methods/dms/uploadFile')(Self);
    require('../methods/dms/removeFile')(Self);
    require('../methods/dms/updateFile')(Self);

    Self.checkRole = async function(ctx, id) {
        const models = Self.app.models;
        const dms = await Self.findById(id);

        return await models.DmsType.hasReadRole(ctx, dms.dmsTypeFk);
    };

    Self.getFile = async function(id) {
        const models = Self.app.models;
        const DmsContainer = models.DmsContainer;
        const dms = await Self.findById(id);
        const pathHash = DmsContainer.getHash(dms.id);
        try {
            await DmsContainer.getFile(pathHash, dms.file);
        } catch (e) {
            if (e.code != 'ENOENT')
                throw e;

            const error = new UserError(`File doesn't exists`);
            error.statusCode = 404;

            throw error;
        }

        const stream = DmsContainer.downloadStream(pathHash, dms.file);

        return [stream, dms.contentType, `filename="${dms.file}"`];
    };
};