import get from 'lodash/get';
import debounce from 'lodash/debounce';
import { containerConnect } from 'Framework/ComponentContainer';
import { t } from 'Framework/i18n';
import createSelector from 'Utils/Function/createSelector';
import { Services } from 'App/ServiceLocator';
import DesignerSelectionToolbox from '../Components/DesignerSelectionToolbox/DesignerSelectionToolbox';
import {
    getSelectedDesignProductionMethod,
    getVectorizedImageColor,
} from 'App/Reducers/DesignArea/Selectors';
import { isColoringDisabled } from 'App/Reducers/DesignArea/Selectors';
import { addCustomFont } from 'App/Reducers/Fonts/Actions';
import { getDefaultFont } from 'App/Reducers/Fonts/Selectors';
import { setVisible } from 'App/Reducers/UI/Actions';
import { FontFaceRepository } from '../Utils/FontFaceRepository';

const getFonts = createSelector(
    state => state.fonts,
    fonts =>
        fonts.map(font => ({
            ...font,
            value: font.family,
        }))
);

const loadFonts = dispatch => textItem => {
    if (!textItem || !textItem.content) {
        return;
    }
    const toggleLoader = show => dispatch(setVisible('globalLoader', show));
    const showLoaderTimeout = window.setTimeout(() => toggleLoader(true), 300);
    FontFaceRepository.collectFromHTML(textItem.content)
        .catch(e => {
            // eslint-disable-next-line no-console
            console.error('Error while loading fonts.', e);
        })
        .finally(() => {
            textItem.build({ triggerChange: true });
            clearTimeout(showLoaderTimeout);
            toggleLoader(false);
        });
};

const mapStateToProps = state => ({
    Component: DesignerSelectionToolbox,
    fonts: getFonts(state),
    colorDisabled: isColoringDisabled(state),
    isActiveBulkName: get(getSelectedDesignProductionMethod(state), 'allowBulkNames'),
    isPortraitMode: state.device.screen.orientation === 'portrait',
    defaultFont: getDefaultFont(state),
    initialColor: getVectorizedImageColor(state),
});

const mapDispatchToProps = dispatch => ({
    updateVisualization: canvas => {
        canvas.selectedObject.x += 1;
        canvas.selectedObject.x -= 1;
    },
    openImageEditDialog: (identifier, canvas, placeholderImageUpdate = false) =>
        Services.designer.openImageEditDialog(identifier, canvas, { placeholderImageUpdate }),
    getTextContent: ({ isBulkName }) =>
        Services.designer.createColorizedTextContent(
            t(isBulkName ? 'textControlbox.bulknames' : 'addVisualElement.initialText'),
            1,
            {
                withPlaceholder: !isBulkName,
            }
        ),
    addCustomFont: customFont => {
        dispatch(addCustomFont(customFont));
    },
    loadFonts: debounce(loadFonts(dispatch), 300),
});

export default containerConnect(mapStateToProps, mapDispatchToProps);
