import isInteger from 'lodash/isInteger';
import get from 'lodash/get';
import { getSelectedDesignProductionMethod } from './Selectors';

export const getDesignElementCount = designData => {
    const objects = get(designData, 'canvasData.objects', []);
    const imagesCount = objects.filter(({ type }) => type === 'Image').length;
    const textsCount = objects.filter(({ type }) => type === 'Text').length;
    return {
        imagesCount,
        textsCount,
        totalCount: imagesCount + textsCount,
    };
};

export const checkDesignElementRestrictions = (designData, designProductionMethod, targetElementType) => {
    const type = typeof targetElementType === 'string' && targetElementType.toLowerCase();
    const { maxImages, maxTexts, maxElements } = designProductionMethod;
    const { imagesCount, textsCount, totalCount } = getDesignElementCount(designData);
    if (maxElements > 0 && totalCount >= maxElements) {
        return {
            type: 'maxElements',
            max: maxElements,
        };
    } else if ((!type || type === 'image') && maxImages > 0 && imagesCount >= maxImages) {
        return {
            type: 'maxImages',
            max: maxImages,
        };
    } else if ((!type || type === 'text') && maxTexts > 0 && textsCount >= maxTexts) {
        return {
            type: 'maxTexts',
            max: maxTexts,
        };
    }
    return null;
};

export const checkDesignElementRestrictionsWithRemovalCount = (designData, designProductionMethod) => {
    const { maxImages, maxTexts, maxElements } = designProductionMethod;
    const { imagesCount, textsCount, totalCount } = getDesignElementCount(designData);
    if (isInteger(maxElements) && totalCount > maxElements) {
        return {
            type: 'maxElements',
            max: maxElements,
            toBeRemovedCount: totalCount - maxElements,
        };
    } else if (isInteger(maxImages) && imagesCount > maxImages) {
        return {
            type: 'maxImages',
            max: maxImages,
            toBeRemovedCount: imagesCount - maxImages,
        };
    } else if (isInteger(maxTexts) && textsCount > maxTexts) {
        return {
            type: 'maxTexts',
            max: maxTexts,
            toBeRemovedCount: textsCount - maxTexts,
        };
    }
    return null;
};

export const getDesignElementAvailability = state => {
    const { maxImages, maxTexts } = getSelectedDesignProductionMethod(state);
    return {
        image: !isInteger(maxImages) || maxImages > 0,
        text: !isInteger(maxTexts) || maxTexts > 0,
    };
};
