import React from 'react';
import { connect } from 'react-redux';
import {
    CanvasProvider,
    CanvasStateProvider,
} from 'redhotmagma-graphics-editor/CanvasInterface/CanvasProvider';
import { TextEditorStateProvider } from 'redhotmagma-graphics-editor/Components/TextEditor/TextEditorStateProvider';
import { withActiveCanvas } from '../../Modules/Designer/withActiveCanvas';
import { getColorPalettes } from '../../Reducers/DesignArea/Selectors';
import get from 'lodash/get';
import first from 'lodash/first';
import createSelector from 'Utils/Function/createSelector';
export const DefaultCanvasProvider = withActiveCanvas(({ canvas, children }) => (
    <CanvasProvider canvas={canvas}>{children}</CanvasProvider>
));

export const DefaultCanvasStateProvider = withActiveCanvas(({ canvas, children }) => (
    <CanvasStateProvider canvas={canvas}>{children}</CanvasStateProvider>
));

const createDefaultStyle = createSelector(
    ({ fonts }) => fonts,
    getColorPalettes,
    (fonts, colorPalettes) => {
        let fontFamily = '';
        let colorValue = '';
        let colorIdentifier = '';
        let colorPaleteIdentifier = '';
        const firstColorPalette = first(colorPalettes);
        const colors = get(firstColorPalette, 'colors', []);
        const firstColor = first(colors);
        const firstFont = first(fonts);
        if (firstColorPalette && firstFont) {
            colorValue = '#' + get(firstColor, 'hex_value', '000000');
            colorIdentifier = get(firstColor, 'identifier', 'black');
            colorPaleteIdentifier = get(firstColorPalette, 'identifier', 'default');
            const escapeQuotes = str => str.replace(/(['"])/g, '\\$1');
            fontFamily = `"${escapeQuotes(firstFont.family)}"`;
        }
        return {
            color: {
                value: colorValue,
                identifier: `{"color": "${colorIdentifier}", "palette": "${colorPaleteIdentifier}"}`,
            },
            fontSize: '16px',
            fontFamily: fontFamily,
        };
    }
);

const mapStateToProps = state => {
    return {
        defaultStyle: createDefaultStyle(state),
    };
};

export const DefaultTextEditorStateProvider = connect(mapStateToProps)(TextEditorStateProvider);
