/* global Venue */
'use strict';

const _ = require('lodash');
const fs = require('fs');
const Path = require("path");
const sanitize = require("sanitize-filename");
const safename = require("safename");
const writeFile = require('write');
const imageType = require('image-type');
//const sharp = require('sharp');

const config = require('../../config');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const models = require('../../core/models');
const { determineProviderInfo, extractProviderInfo } = require('../../helpers/providers.helper');

const providerComposer = (multimedia) => {
    return extractProviderInfo(multimedia.code)
}

/*const _generateThumbFileName = function (fileName, prefix) {
    prefix = prefix || config.uploads.thumb_prefix;
    return Path.join(
        Path.dirname(fileName),
        prefix + Path.basename(fileName)
    );
};

const _uploadFile = function (file, filename, options) {
    var defaultOptions = {
        thumb: false,
        thumbSize: config.uploads.thumb_size,
    }

    options = _.defaults(options || {}, defaultOptions);
    var diskFilename = Path.join(config.uploads.path, filename);

    return new Promise(function (resolve, reject) {
        if (!imageType(file.buffer)) {
            reject('No es un fichero de imagen');
        };

        fs.writeFile(diskFilename, file.buffer, function (error) {
            if (error) {
                console.log(error);
                reject(error);
            } else {
                if (options.thumb) {
                    var diskThumbFilename = _generateThumbFileName(diskfilename);
                    sharp(file.buffer).resize(options.thumbSize).toBuffer()
                        .then(function (data) {
                            fs.writeFile(diskThumbFilename, data, function (error) {
                                if (error) {
                                    console.log(error);
                                    reject(error);
                                } else {
                                    resolve({
                                        fileName: fileName,
                                        diskFilename: diskFilename,
                                    });
                                }
                            });
                        })
                        .catch(function (error) {
                            console.log(error);
                            reject(error);
                        });
                } else {
                    resolve();
                }
            }
        });
    });
}*/

const extraMethods = {
    removeFile: function (filename) {
                
        const diskFilename = Path.join(config.uploads.path, filename);
        const diskThumbFilename = _generateThumbFileName(diskFilename);

        return new Promise(function(resolve, reject) {
            fs.unlink(diskFilename, function (error) {
                fs.unlink(diskThumbFilename, function (error) {
                    resolve();
                });
            });
        });
    },
    

    uploadFile: async function (file, filename, data, context) {
        const upload = await _uploadFile(file, filename);
        return await models.MultimediaFile.create({
            name: data.name,
            description: data.description,
            provider: 'cdn',
            class: 'picture',
            url: filename,
            userId: context && context.user ? context.user.id : undefined
        })
    },

    beforeCreate: function(values, context) {
        /*if (values.provider != 'cdn') {
            var info = determineProviderInfo(values.url);

            values.provider = info.provider;
            values.code = info.code;
            values.class = info.class;
        }*/
        console.log(values);
        return values;
    },

    afterFetchOne: async (result, params, context) => {
        if (!result) {
            return result;
        }
        
        const multimedia = result.toJSON();


        if (multimedia.provider === 'vimeo') {
            multimedia.providerInfo = await providerComposer(multimedia);
        }
        return multimedia;
    },

}

module.exports = generateService(models.MultimediaFile, extraMethods); 