import React from "react";
import {withRouter} from "react-router";
import {units} from "../../../constants/units";
import style from "./volumeFilter.module.sass";
import FancyCheckbox from "../../inputs/filterCheckbox/filterChechbox";
import {connect} from "react-redux";
import {getFilterSettings, getGoodsByGroup} from "../../../actions/actionCreator";
const queryString = require('query-string');

const VolumeFilter = (props) => {

    const changeVolume = (volume, change) => {
        const rows = (window.pageYOffset + document.documentElement.clientHeight) / 200;

        const settingsFilterClone
            = Object.assign({}, props.settings, {rows: rows, blackListIdsGoods: []});

        if(!change) {
            settingsFilterClone.volume.push(volume);
        }else if(change) {

            settingsFilterClone.volume
                .splice(settingsFilterClone.volume.indexOf(volume), 1);
        }

        props.setFilterSettings(settingsFilterClone);
        const stringified = queryString.stringify(settingsFilterClone, {arrayFormat: 'bracket'});
        props.history.push(window.location.pathname + "?" + stringified);
        props.getGoodsByGroup(props.match.params.number, settingsFilterClone);
    };

    console.log(props.filterElements);

        return(
            <div className={style.mainContainer}>
                <h1>Об'ем</h1>
                {
                    props.filterElements.goodsVolumes && props.filterElements.goodsVolumes.map((elem, id) => (
                        <FancyCheckbox
                            indexKey={id}
                            idCheckbox={`volume_${elem.valueAttribute}`}
                            valueLabel={elem.valueAttribute + units[elem.nameAttribute]}
                            typeCheckbox={"volume"}
                            key={id}
                            onChange={changeVolume}
                            count={elem.count}
                            checked={props.settings.volume.indexOf(elem.valueAttribute + units[elem.nameAttribute]) !== -1}
                        />
                    ))
                }
            </div>
        )
};

const mapStateToProps = state => {
    const { settings, isFetching, error } = state.goodsReducers;
    const {filterElements} = state.filterReducers;


    return {
        settings, isFetching, error, filterElements
    }
};

const mapDispatchToProps = (dispatch) => ({
    setFilterSettings: (filterData) => dispatch(getFilterSettings(filterData)),
    getGoodsByGroup: (id, query) => dispatch(getGoodsByGroup(id, query, true, false))
});

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(VolumeFilter));