import { isPlaceholderContent, isValidHex } from '../DesignArea/Selectors';
import { hexToRgb } from '@material-ui/core/styles';
import { getRgbValuesFromString, isColorTooBright } from '../../Services/DesignDataService';
import find from 'lodash/find';
import get from 'lodash/get';
import size from 'lodash/size';

export const hasBackgroundColor = colors => {
    return colors
        .map(color => (isValidHex(color.value) ? hexToRgb(color.value) : color.value || 'rgb(0, 0, 0)'))
        .map(getRgbValuesFromString)
        .some(isColorTooBright);
};

export const getAggregatedColors = colors => {
    return Object.keys(colors).reduce((uniqColors, colorKey) => {
        const color = colors[colorKey];
        if (find(uniqColors, c => c.identifier === color.identifier)) {
            return uniqColors;
        }
        return { ...uniqColors, [colorKey]: color };
    }, {});
};

export const getAggregatedColorCount = colors => size(getAggregatedColors(colors));

export const getInitialMaxColorAmount = state => {
    return get(state, 'imageGallery.selectedImage.operations.vectorizeMaxColorAmount', undefined);
};

export const getOriginalColorsMap = state => {
    return get(state, 'imageGallery.selectedImage.operations.vectorizeOriginalColorsMap', {});
};

export const getColorKeysForAggregatedColor = (vectorizeColorsMap, colorKey) => {
    let colors = [];
    //loop over the elements and detect all colors with the same mapped value
    const colorToColorize = vectorizeColorsMap[colorKey];
    for (const colorKey in vectorizeColorsMap) {
        if (!vectorizeColorsMap.hasOwnProperty(colorKey)) {
            continue;
        }
        if (vectorizeColorsMap[colorKey].identifier === colorToColorize.identifier) {
            colors.push(colorKey);
        }
    }
    return colors;
};

export const isPlaceholderObject = obj => {
    return (
        (obj.type === 'Text' && isPlaceholderContent(obj.content)) ||
        (obj.type === 'Image' && obj.imageData.isPlaceHolderImage)
    );
};
