import React, {Component} from 'react';
import {connect} from 'react-redux';
import ActiveOrderItem from './ActiveOrderItem.jsx';
import HistoryOrderItem from './HistoryOrderItem.jsx';
import {WiaasTable, WiaasTableHeader, WiaasTableBody} from '../../../mainComponents/table/WiaasTable.jsx';
import {orderTexts} from '../../../constants/ordersConstants';

class OrderList extends Component {
    constructor(props) {
        super(props);
        this.getHeadersByType = this.getHeadersByType.bind(this);
    }

    getHeadersByType(type) {
        const activeOrdersHeader = [
            orderTexts.headers.ORDER,
            orderTexts.headers.REFERENCE,
            orderTexts.headers.ORDER_DATE,
            orderTexts.headers.ESTIMATED_DATE,
            orderTexts.headers.COMMERCIAL_LEAD,
            orderTexts.headers.AMOUNT,
            orderTexts.headers.STATUS,
            ''
        ];

        const historyOrdersHeader = [
            orderTexts.headers.ORDER,
            orderTexts.headers.REFERENCE,
            orderTexts.headers.ORDER_DATE,
            orderTexts.headers.DELIVERY_DATE,
            orderTexts.headers.COMMERCIAL_LEAD,
            orderTexts.headers.AMOUNT,
            orderTexts.headers.STATUS,
            orderTexts.headers.END_OF_LIFE,
            ''
        ];

        if(this.props.isCompanyAdmin && this.props.isViewAllOrdersChecked[type]) {
            activeOrdersHeader.splice(2, 0, orderTexts.headers.PLACED_BY);
            activeOrdersHeader.join();
            historyOrdersHeader.splice(2, 0, orderTexts.headers.PLACED_BY);
            historyOrdersHeader.join();
        }

        return type === 'active' ? activeOrdersHeader : historyOrdersHeader;
    }

    render() {
        const {orders, type, isCompanyAdmin, isViewAllOrdersChecked} = this.props;
        const TagName = type && type === 'active' ? ActiveOrderItem : HistoryOrderItem;

        return (
            <div>
                <WiaasTable>
                    <WiaasTableHeader headers={this.getHeadersByType(type)}/>
                    <WiaasTableBody>
                        {
                            orders &&
                            orders.map((order, index) =>
                                (('isMyOrder' in order && order.isMyOrder) || (isCompanyAdmin && isViewAllOrdersChecked[type])) &&
                                <TagName key={order.orderNumber} order={order} />
                             )
                        }
                    </WiaasTableBody>
                </WiaasTable>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    isCompanyAdmin: state.auth.isCompanyAdmin,
    isViewAllOrdersChecked: state.ordersReducer.isViewAllOrdersChecked
});
export default connect(mapStateToProps)(OrderList);
