import React from 'react';
import {withNamespaces} from 'react-i18next';

import Loading from "../../component/Loading";
import {withPusher} from "../../component/PushToApi/Pusher";

import {withTheme, injectSheet} from '../../lib/theme';
import {ApiRequest, POST} from '../../lib/ApiRequest';
import OrdersList from './OrdersList';

const theming = theme => ({
    button: {
        fontSize: '0.875rem',
        background: 'none',
        padding: theme.gutter.base + 'px ' + theme.gutter.base * 2 + 'px',
        '&:first-child': {
            paddingLeft: 0,
        },
        '&:last-child': {
            paddingRight: 0,
        }
    },
    subTitle: {
        margin: 0
        //margin: '-12px 0 6px 0',
    }
});

const initialState = {
    orders: [],
    hasLocales: false,
    localeActive: false,
    localesPossible: [],
    locales: [],
    productTypesPossible: [],
    loaded: false,
    savingStateUpdate: {}
};

class Orders extends React.Component {

    state = initialState;

    componentWillUnmount() {
        this.setState(initialState);
    }

    //
    // Api Fetch and Push

    createSavingStateUpdate(name, val) {
        const savingStateUpdate = {...this.state.savingStateUpdate};
        savingStateUpdate[name] = val;
        return savingStateUpdate;
    }

    fetch() {
        this.setState({loaded: 'progress'});
        (new ApiRequest('api', POST, 'shop/order/list' + (this.props.match.params.state ? '/' + this.props.match.params.state : '')))
            .debug(true)
            .header({})
            .exec()
            .then((res) => {
                if(res && res.data) {
                    if(res.data) {

                        this.setState({
                            orders: res.data,
                            loaded: true
                        });
                    }
                    if(res.data.error) {
                        this.setState({
                            loaded: 'error'
                        });
                    }
                } else {
                    this.setState({
                        loaded: 'error'
                    });
                }
            })
            .catch(() => {
                this.setState({
                    loaded: 'error'
                });
            });
    }

    pushStateUpdate = (index, order_id, new_state) => {
        const endpoint = 'shop/order/update/' + order_id;

        const orders = [...this.state.orders];
        if(this.props.match.params.state && 'all' !== this.props.match.params.state && this.props.match.params.state !== new_state) {
            orders.splice(index, 1);
        } else {
            let order = {...orders[index]};
            order.state = new_state;
            orders[index] = order;
        }
        this.setState({orders: orders});

        this.props.addPushing(
            {
                name: 'pushStateUpdate',
                context: endpoint,
                push: (resolve, reject) => {
                    this.setState({savingStateUpdate: this.createSavingStateUpdate(order_id, 'progress')});

                    (new ApiRequest('api', POST, endpoint, {state: new_state}))
                        .debug(true)
                        .header({})
                        .exec()
                        .then((res) => {
                            if(res && res.data) {
                                resolve(res.data);
                            } else {
                                reject();
                            }
                        })
                        .catch(() => {
                            reject();
                        });
                }
            })
            .then((data) => {
                if(data.error) {
                    this.setState({savingStateUpdate: this.createSavingStateUpdate(order_id, 'error')});
                    return;
                }

                this.setState({
                    savingStateUpdate: this.createSavingStateUpdate(order_id, 'success'),
                });

                setTimeout(() => {
                    this.setState({savingStateUpdate: this.createSavingStateUpdate(order_id, false)});
                }, 4000);
            })
            .catch((data) => {
                if(!data.cancelled) {
                    this.setState({savingStateUpdate: this.createSavingStateUpdate(order_id, 'error')});
                }
            });
    };

    //
    // Default Lifecycles

    shouldComponentUpdate(nextProps, nextState) {

        return true;
    }

    componentDidUpdate(prevProps) {
        if(prevProps.match.params.state !== this.props.match.params.state ||
            prevProps.match.params.state !== this.props.match.params.state) {
            this.fetch();
        }
    }

    componentDidMount() {
        this.fetch();
    }

    render() {
        const {t} = this.props;
        const {
            orders
        } = this.state;

        return (
            <React.Fragment>
                <h1>{t('title')}</h1>
                {
                    true === this.state.loaded ?
                        (
                            <React.Fragment>
                                {/*<OrdersControl/>*/}
                                <OrdersList orders={orders}
                                            pushStateUpdate={this.pushStateUpdate}
                                            savingStateUpdate={this.state.savingStateUpdate}/>
                            </React.Fragment>
                        ) :
                        ('progress' === this.state.loaded || 'error' === this.state.loaded ?
                            <Loading style={{
                                wrapper: {margin: 0},
                                item: ('error' === this.state.loaded ? {borderColor: this.props.theme.errorColor} : {}),
                            }}/> :
                            null)
                }
            </React.Fragment>
        )
    };
}

export default withNamespaces('page--shop-order')(withPusher(withTheme(injectSheet(theming)(Orders))));