import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Alert, Row, Col} from 'reactstrap';
import WiaasBox from '../../mainComponents/box/WiaasBox.jsx';
import {getActiveOrders, getHistoryOrders} from '../../actions/orders/ordersActions';
import OrderList from './components/OrderList.jsx';
import OrderListHeader from './components/OrderListHeader.jsx';
import {orderTexts} from '../../constants/ordersConstants';

class OrdersDataContainer extends Component {
    componentDidMount() {
        this.props.dispatch(getActiveOrders());
        this.props.dispatch(getHistoryOrders());
    }

    hasCurrentCustomerOrders(orders) {
        return orders.some((order) => order.isMyOrder);
    }

    render() {
        const {activeOrders, historyOrders, type, isLoading} = this.props;
        const orders = type ? type === 'active' ? activeOrders : historyOrders : {};
        const mainTitleOrder = type.charAt(0).toUpperCase() + type.slice(1);

        return (
            <Row>
                <Col lg="12" xs="12">
                    <WiaasBox id={type + "-orders-container"} mainTitle={mainTitleOrder + " Orders"} customHeader={OrderListHeader} customHeaderParams={type}>
                        {
                            isLoading &&
                            <div className="loader">
                                <i className="fa fa-spinner fa-spin fa-3x" aria-hidden="true"></i>
                            </div>
                        }
                        { (orders  && !isLoading) &&
                           <OrderList orders={orders} type={type}/>
                        }
                        {
                            ((orders && orders.length === 0 && !isLoading) || (orders && !this.hasCurrentCustomerOrders(orders))) &&
                            <Alert color="info">{orderTexts.labels.NO_RECORDS}</Alert>
                        }
                    </WiaasBox>
                </Col>
            </Row>
        );
    }
}

const mapStateToProps = (state) => ({
    activeOrders: state.ordersReducer.activeOrders,
    historyOrders: state.ordersReducer.historyOrders,
    isLoading: state.ordersReducer.isLoading
});

export default connect(mapStateToProps)(OrdersDataContainer);
