const md5 = require('md5');

module.exports = function(Self) {
    Self.setup = function() {
        Self.super_.setup.call(this);

        this.remoteMethod('allowedContentTypes', {
            description: 'Returns a list of allowed contentTypes',
            accessType: 'READ',
            returns: {
                type: ['Object'],
                root: true
            },
            http: {
                path: `/allowedContentTypes`,
                verb: 'GET'
            }
        });
    };

    /**
     * Returns a container instance
     * If doesn't exists creates a new one
     *
     * @param {String} name Container name
     * @return {Object} Container instance
     */
    Self.container = async function(name) {
        const models = Self.app.models;
        let container;
        try {
            container = await models[this.modelName].getContainer(name);
        } catch (err) {
            if (err.code === 'ENOENT') {
                container = await models[this.modelName].createContainer({
                    name: name
                });
            } else throw err;
        }

        return container;
    };

    Self.getHash = function(id) {
        return md5(id.toString()).substring(0, 3);
    };

    Self.getFileExtension = function(fileName) {
        return fileName.split('.').pop().toLowerCase();
    };

    Self.allowedContentTypes = async function() {
        const connector = this.dataSource.connector;
        const allowedContentTypes = connector.allowedContentTypes;
        return allowedContentTypes;
    };
};