import React from "react";
import {withRouter} from "react-router";
import style from "./genderFilter.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 GenderFilter = (props) => {

    const changeGender = (gender, change) => {
        const rows = (window.pageYOffset + document.documentElement.clientHeight) / 200;
        const settingsFilterClone
            = Object.assign({}, props.settings, {rows: rows, blackListIdsGoods: []});

        if(!change) {
            settingsFilterClone.gender.push(gender);

        }else if(change) {

            settingsFilterClone.gender
                .splice(settingsFilterClone.gender.indexOf(gender, 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);

    };


        return(
            <div className={style.mainConrtainer}>
                <h1>Пол</h1>
                <div className={style.gender}>
                    {
                        props.filterElements.goodsGender && props.filterElements.goodsGender.map((elem, id) => (
                            <FancyCheckbox
                                indexKey={id}
                                idCheckbox={`gender_${elem.goodsGender}`}
                                valueLabel={elem.goodsGender}
                                typeCheckbox={"gender"}
                                key={id}
                                onChange={changeGender}
                                count={elem.count}
                                checked={props.settings.gender.indexOf(elem.goodsGender) !== -1}
                            />
                        ))
                    }
                </div>
            </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)(GenderFilter));