import { Dimensions, Ratio } from './config';

function readFile(imageFile) {
    return new Promise(resolve => {
        let reader = new FileReader();

        reader.onload = ({ target }) => {
            resolve(target.result);

            // очищаем file picker для хромиумов
            target.value = '';
        };

        reader.readAsDataURL(imageFile);
    });
}

function getError(imageUrl) {
    return new Promise(resolve => {
        let image = new Image();

        image.onload = () => {
            if (!image.width || !image.height) {
                return resolve('invalid_image_size');
            }

            if (Math.min(image.width, image.height) < Dimensions.MIN) {
                return resolve('image_too_small');
            }

            if (Math.max(image.width, image.height) > Dimensions.MAX) {
                return resolve('image_too_big');
            }

            const ratio = image.width / image.height;

            if (ratio < Ratio.MIN) {
                return resolve('image_too_narrow');
            }

            if (ratio > Ratio.MAX) {
                return resolve('image_too_wide');
            }

            resolve();
        };

        image.onerror = () => {
            resolve('failed_to_load_image');
        };

        image.src = imageUrl;
    });
}

export default function validateFile(file) {
    return readFile(file).then(getError);
}
