/* global Venue */
'use strict';

const _ = require('lodash');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const models = require('../../core/models');
const cdnHelper = require('../../helpers/cdn.helper');
const { extractProviderInfo } = require('../../helpers/providers.helper');

const providerComposer = (multimedia) => {

    if (multimedia.provider === 'vimeo') {
        multimedia.providerInfo = extractProviderInfo(multimedia.code)
    } else if (multimedia.provider === 'cdn') {        
        multimedia.url = cdnHelper.getCDNMediaUrl(multimedia.url);
    }

    return multimedia;
}

const extraMethods = {
    afterFetchAll: (result, params, context) => {

        if (!result.count) {
            return result;
        }

        let rows = result.rows.map(function(row) {
            let result = row.toJSON();

            delete result.multimediaFile.id;

            result = Object.assign(result, result.multimediaFile, { multimediaFile: undefined })

            delete result.createdAt;
            delete result.updatedAt;
            delete result.userId;

            return providerComposer(result);
        });

        return {
            count: result.count,
            rows: rows
        }
    },

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

        return providerComposer(multimedia);
    },

    

}

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