import withWidth from '@material-ui/core/withWidth';
import { containerConnect } from 'Framework/ComponentContainer';
import createSelector from 'Utils/Function/createSelector';
import findIndex from 'lodash/findIndex';
import AddGalleryImage from '../Components/AddGalleryImage';
import Progress from 'App/Shared/Components/Progress/Progress';
import {
    dismissError,
    fetchTags,
    selectTags,
    WN_LOAD_IMAGES,
    WN_LOAD_TAGS,
} from 'App/Reducers/ImageGallery/Actions';
import { createBackgroundWorkStateSelector } from 'App/Reducers/UI/Selectors';
import { getUrl } from 'App/Utils/getUrl';

const getTags = createSelector(
    imageGalleryState => imageGalleryState.tags,
    imageGalleryState => imageGalleryState.selectedTag,
    imageGalleryState => imageGalleryState.selectedTags,
    (tags, selectedTag, selectedTags) =>
        tags.map(tag => ({
            title: tag.title,
            checked:
                selectedTags &&
                findIndex(selectedTags, selectedTag => {
                    if (selectedTag.title === tag.title) {
                        return selectedTag.checked;
                    }
                }) > -1,
        }))
);

const getGalleryImages = createSelector(
    imageGalleryState => imageGalleryState.gallery,
    images =>
        images.map(image => ({
            ...image,
            url: getUrl(image.thumbUrl),
        }))
);

const getLoadingState = createBackgroundWorkStateSelector(WN_LOAD_TAGS, WN_LOAD_IMAGES);

const mapStateToProps = state => ({
    Component: AddGalleryImage,
    ProgressComponent: Progress,
    tags: getTags(state.imageGallery),
    images: getGalleryImages(state.imageGallery),
    loading: getLoadingState(state.ui),
});

const mapDispatchToProps = dispatch => ({
    loadTags: () => dispatch(fetchTags()),
    onSelectTag: tags => dispatch(selectTags(tags)),
    dismissError: () => dispatch(dismissError()),
});

export default withWidth()(containerConnect(mapStateToProps, mapDispatchToProps));
