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

const SortBarElement = (props) => {
    const {name, sort, order, key} = props;

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

        if(sort) {
            settingsFilterClone.sort = e.target.dataset.sort;
        }

        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.settings);

    };


    return(
        <div
            className={
                !sort
                    && props.settings.order === order
                    || props.settings.sort === sort ? style.barElementActive : style.barElement
            }

             data-sort={sort}
             data-order={order}
             onClick={filterHandler}
             key={key}
        >

            {name}
        </div>
    )
};

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

    return {
        settings, isFetching, error
    }
};

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

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