'use strict';

var axios = require('../../node_modules/axios/lib/axios.js');
var index = require('../../node_modules/jimp/es/index.js');
var dimension = require('../../design/dimension.js');

let imageHolder = {};
const ImageUtil = {
    downloadAndSaveToStorage: async (uri) => {
        const response = await axios.get(uri, { responseType: 'arraybuffer' });
        const buffer = Buffer.from(response.data, 'binary');
        const { height, width } = await ImageUtil.dimension(buffer);
        imageHolder[uri] = { buffer, width, height };
    },
    getFromStorage: (uri) => imageHolder[uri],
    clearStorage: () => {
        imageHolder = {};
    },
    dimension: async (image) => {
        const j = await index.read(image);
        const width = j.bitmap.width;
        const height = j.bitmap.height;
        const scale = dimension.ProblemDimension.width / width;
        return {
            width: Math.floor(width * scale),
            height: Math.floor(height * scale),
        };
    },
};

exports.ImageUtil = ImageUtil;
