import React from 'react';
import {withContextConsumer} from "@formanta/react";
import {ApiRequest, POST} from "../../../lib/ApiRequest";
import {cancelPromise} from "../../../component/cancelPromise";
import {withApiControl} from "../../../component/ApiControl";
import {withPusher, Pushing} from "../../../component/Pusher/Pusher";

const StoreOrderContext = React.createContext({});

class StoreOrderProviderBase extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            orders: [],
            loadingOrders: false,
            loadOrderList: this.loadOrderList,
            updateOrderState: this.updateOrderState
        };
    }

    doApiRequest(type, endpoint, name, data = {}) {
        return new Pushing(
            name,
            endpoint,
            (resolve, reject) => {
                (new ApiRequest('api', type, endpoint, data))
                    .debug(true)
                    .header({})
                    .exec()
                    .then((res) => {
                        if(res && res.data) {
                            if(res.data.error) {
                                return Promise.reject(res);
                            }
                            resolve(res.data);
                        } else {
                            reject();
                        }
                    })
                    .catch((err) => {
                        this.props.handleApiFail(err, name);
                        reject(err);
                    });
            }
        )
    }

    /**
     * @todo make loadingOrders using state also, then remove force loading where needed
     * @param state
     * @param forceLoad
     */
    loadOrderList = (state, forceLoad = false) => {
        if(true !== this.state.loadingOrders || forceLoad) {

            this.setState({loadingOrders: 'progress'});

            (new ApiRequest('api', POST, 'shop/order/list' + (state ? '/' + state : '')))
                .debug(true)
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        this.setState({
                            orders: res.data,
                            loadingOrders: true
                        })
                    } else {
                        this.setState({
                            loadingOrders: 'error'
                        });
                    }
                })
                .catch((err) => {
                    this.props.handleApiFail(err, 'listing Orders');
                    if(err && !err.cancelled) {
                        this.setState({
                            loadingOrders: 'error'
                        });
                    }
                });
        }
    };

    updateOrderState = (index, order_id, old_state, new_state) => {
        const {execPushing} = this.props;
        const endpoint = 'shop/order/update/' + order_id;

        const orders = [...this.state.orders];
        if(old_state && 'all' !== old_state && old_state !== new_state) {
            orders.splice(index, 1);
        } else {
            let order = {...orders[index]};
            order.state = new_state;
            orders[index] = order;
        }
        this.setState({orders: orders});
        return execPushing(
            this.doApiRequest(POST, endpoint, 'updateOrderState', {state: new_state})
        );
    };

    render() {
        return (
            <StoreOrderContext.Provider value={this.state}>
                {this.props.children}
            </StoreOrderContext.Provider>
        );
    }
}

const StoreOrderProvider = cancelPromise(withPusher(withApiControl(StoreOrderProviderBase)));

const storeOrder = withContextConsumer(StoreOrderContext.Consumer);

export {StoreOrderProvider, storeOrder};