const Path = require("path");
const config = require('../config');
const sanitize = require("sanitize-filename");
const safename = require("safename");
const unf = require('unique-file-name');

const assetsUrl = config.cdn.hostname;

const CDN_PATHS = {
    BLOG: "blog/",
    CITIES: "cities/",
    EVENT: "events/", 
    PROFILE: "profile/",
    SPEAKERS: "speakers/",
    WALLPAPERS: "wallpapers/",
    XLSX: "xlsx/",  
    PARTNERS: "partners/",  
};
const dummyMedia = encodeURI(`${assetsUrl}/defaultProfile.png`);

const sanitizeFilename = (filename) => safename(sanitize(filename, { replacement: "_" }));

const getUniqueName = function (_path, _filename) {
    const namer = unf({
        format: '%48b_%2i%4e',
        dir: _path
    });
    return namer(_filename)
}

const getCDNMediaUrl = (mediaUri) => {
    if (mediaUri) {
        const pathParsed = mediaUri.indexOf("media") == 0 ? mediaUri.substr("media/".length, mediaUri.length) : mediaUri;
        return encodeURI(encodeURI(`${assetsUrl}/${pathParsed}`));
    }
    else {
        return encodeURI(dummyMedia);
    }
}

const getCDNCityMediaUrl = (cityName) => encodeURI(`${assetsUrl}/${CDN_PATHS.CITIES}/${cityName}.jpg`);

const getCDNCurrentPartnersJSON = encodeURI(`${assetsUrl}/${CDN_PATHS.PARTNERS}partners_current.json`);
const getCDNPastPartnersJSON = encodeURI(`${assetsUrl}/${CDN_PATHS.PARTNERS}partners_past.json`);

const getCDNPath = (type = '') => {
    var cdnPath = '';
    switch (type) {
        case 'speaker':
            cdnPath = CDN_PATHS.SPEAKERS;
            break;
        case 'event':
            cdnPath = CDN_PATHS.EVENT;
            break;

        case 'post':
            cdnPath = CDN_PATHS.BLOG;
            break;

        case 'xlsx':
            cdnPath = CDN_PATHS.XLSX;
            break;

        case 'partners':
            cdnPath = CDN_PATHS.PARTNERS;
            break;
            
        default:
            var _date = new Date();
            cdnPath = _date.getFullYear() + '/' + (_date.getMonth() + 1) + '/'; 
            break;
    }
    return Path.join(config.uploads.path, cdnPath);
}

const getCDNFilenameWithPath = (filename, type) => {
    var cdnPath = '';
    switch (type) {
        case 'speaker':
            cdnPath = CDN_PATHS.SPEAKERS;
            break;
        case 'event':
            cdnPath = CDN_PATHS.EVENT;
            break;

        case 'post':
            cdnPath = CDN_PATHS.BLOG;
            break;

        default:
            var _date = new Date();
            cdnPath = _date.getFullYear() + '/' + _date.getMonth() + '/';
            break;
    }
    return Path.join(cdnPath, sanitizeFilename(filename));
}

module.exports = {
    sanitizeFilename,
    CDN_PATHS,
    getCDNCityMediaUrl,
    getCDNMediaUrl,
    getCDNPath,
    getCDNFilenameWithPath,
    getCDNCurrentPartnersJSON,
    getCDNPastPartnersJSON,    
    getUniqueName
}