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

const MadeInFilter = (props) => {
    const {filterElements, settings} = props;
    const {goodsMadeIn} = filterElements;

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

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

        if(!change) {
            settingsFilterClone.madeIn.push(country);

        }else if(change) {

            settingsFilterClone.madeIn
                .splice(settingsFilterClone.madeIn.indexOf(country), 1);

        }
        props.getFilterSettings(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.settings);

        return(
            <div className={style.mainContainer}>
                <h1>Страна изготовитель:</h1>
                {
                    goodsMadeIn && goodsMadeIn.map((elem, id) => (
                        <FancyCheckbox
                            indexKey={id}
                            idCheckbox={`countryFragrance_${elem.goodsMadeIn}`}
                            valueLabel={elem.goodsMadeIn}
                            typeCheckbox={"gender"}
                            key={id}
                            onChange={changeMadeIn}
                            count={elem.count}
                            checked={settings.madeIn.indexOf(elem.goodsMadeIn) !== -1}
                        />
                    ))
                }
            </div>
        );
};

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

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

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

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