import React from 'react';
import PropTypes from 'prop-types';
import { Services } from 'App/ServiceLocator';
import { containerConnect } from 'Framework/ComponentContainer';
import { t } from 'Framework/i18n';
import AddVisualElement from '../Components/AddVisualElement';
import { WN_LOAD_TAGS } from 'App/Reducers/ImageGallery/Actions';
import { createBackgroundWorkStateSelector } from 'App/Reducers/UI/Selectors';
import Progress from 'App/Shared/Components/Progress/Progress';
import { withCanvasState, withCanvas } from 'redhotmagma-graphics-editor/CanvasInterface/CanvasProvider';
import { hasLastEditedDesignArea } from '../../../Reducers/DesignArea/Selectors';
import { getDesignElementAvailability } from '../../../Reducers/DesignArea/DesignElementSelectors';

class AddVisualElementContainer extends React.Component {
    static propTypes = {
        deselectImage: PropTypes.func,
        imageGallery: PropTypes.object,
        canvas: PropTypes.object,
        selectedObject: PropTypes.object,
        AddVisualElementComponent: PropTypes.func,
        loading: PropTypes.bool,
        autoHide: PropTypes.bool,
        hasLastEditedDesignArea: PropTypes.bool,
    };

    static defaultProps = {
        autoHide: false,
    };

    openAddImagePanel = async () => {
        const { canvas } = this.props;

        Services.designer.openImageEditDialog(null, canvas);
    };

    render() {
        const { canvas, autoHide, selectedObject, AddVisualElementComponent, loading } = this.props;

        if (autoHide && selectedObject) {
            return null;
        }
        return (
            <React.Fragment>
                <AddVisualElementComponent
                    boxed={true}
                    onAddImageClick={this.openAddImagePanel}
                    onAddTextClick={() => {
                        Services.designer.addText(canvas, t('addVisualElement.initialText'));
                    }}
                    {...this.props}
                />
                <Progress loading={loading} />
            </React.Fragment>
        );
    }
}

export const AddVisualElementContainerWithCanvasState = withCanvas(
    withCanvasState(AddVisualElementContainer)
);

const getLoadingState = createBackgroundWorkStateSelector(WN_LOAD_TAGS);

const mapStateToProps = state => {
    const { imageGallery } = state;
    const designElementAvailability = getDesignElementAvailability(state);

    return {
        Component: AddVisualElementContainerWithCanvasState,
        AddVisualElementComponent: AddVisualElement,
        boxed: true,
        imageGallery,
        loading: getLoadingState(state.ui),
        hasLastEditedDesignArea: hasLastEditedDesignArea(state.designArea),
        enableAddText: designElementAvailability.text,
        enableAddImage: designElementAvailability.image,
    };
};

export default containerConnect(mapStateToProps);
