import React from "react";
import {withRouter} from "react-router";
import style from "./goodsTypeFilter.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 GoodsTypeFilter = (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.typeGoods.push(gender.toLowerCase());
        }else if(change) {
            settingsFilterClone.typeGoods
                .splice(settingsFilterClone.typeGoods.indexOf(gender.toLowerCase()), 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}>
                    <FancyCheckbox idCheckbox={`sale`}
                                   valueLabel={"Распродажа"}
                                   onChange={changeGender}
                                   checked={props.settings.typeGoods
                                       .indexOf("Распродажа".toLowerCase()) !== -1}
                    />

                    <FancyCheckbox idCheckbox={`new`}
                                   valueLabel={"Новинки"}
                                   onChange={changeGender}
                                   checked={props.settings.typeGoods
                                       .indexOf("Новинки".toLowerCase()) !== -1}
                    />
                </div>
            </div>
        );
};

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

    return {
        settings, isFetching, error
    }
};

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

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