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


const BrandFilter = (props) => {
    const invertBrands = invert(brands);


     const changeBrand = (brand, change) => {

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

         brand = brands[brand];

        if(!change) {
            settingsFilterClone.brand.push(brand);
        }else {
            settingsFilterClone.brand
                .splice(settingsFilterClone.brand.indexOf(brand), 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.brand}>
                <h1>Бренд</h1>
                <div className={style.brands}>
                    {
                        props.filterElements.goodsBrandId && props.filterElements.goodsBrandId.map((elem, id) => (
                            <FancyCheckbox
                                indexKey={id}
                                idCheckbox={`brand${elem.goodsBrandId}`}
                                valueLabel={invertBrands[elem.goodsBrandId]}
                                typeCheckbox={"brand"}
                                key={id}
                                onChange={changeBrand}
                                count={elem.count}
                                checked={props.settings.brand.indexOf(elem.goodsBrandId + '') !== -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)(BrandFilter));