'use strict';

const multer = require('multer');
const path = require('path');
const moment = require('moment');
const fs = require('fs-extra');

const fileStorageConfig = config.get('fileStorage');
const maxUploadSize = parseInt(config.get('maxUploadSize')) ?
  parseInt(config.get('maxUploadSize')) : SharedConstants.DEFAULT_MAX_UPLOAD_SIZE;

const SUBDIR_DAILY      = "Daily";
const SUBDIR_MONTHLY    = "Monthly";
const SUBDIR_ANNUAL     = "Annual";
const format            = "YYYYMMDD";

const getSubDirectory = () => {
    // SUBDIR_MONTHLY as default
    let subDir = moment().startOf('month').format(format).toString();

    if (fileStorageConfig && fileStorageConfig.subDirectoryCreationFrequency) {
        if (fileStorageConfig.subDirectoryCreationFrequency === SUBDIR_DAILY) {
            subDir = moment().format(format).toString();
        } else if (fileStorageConfig.subDirectoryCreationFrequency === SUBDIR_ANNUAL) {
            subDir = moment().startOf('year').format(format).toString();
        }
    }

    return subDir;
};

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        fs.exists(fileStorageConfig.path).then(exists => {
            if (exists) {
                fs.access(fileStorageConfig.path, fs.constants.W_OK, (err) => {
                    if (err) {
                        logger.error("No Write permission for: " 
                            + fileStorageConfig.path);
                        cb("Could not upload because the app doesn't have the right " 
                            + "access for upload directory.");
                    } else {
                        const subDir = getSubDirectory();
                        let dest = subDir !== '' ?
                            path.join(fileStorageConfig.path, subDir) : 
                            fileStorageConfig.path;

                        fs.mkdir(dest, { recursive: true }).then(() => {
                            cb(null, dest);
                        });
                    }
                });                
            } else {
                logger.error("Path does not exist: " + fileStorageConfig.path);
                cb('Could not upload because the destination directory does not exist.');
            }
        });
    }
});

exports.upload = multer({
    limits: { fileSize: (maxUploadSize * 1024 * 1024)}, // maxUploadSize in mb, so converting to mb to bytes.
    storage: storage
});

exports.getSubDirectory = getSubDirectory;