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

const StoreProductTypeContext = React.createContext({});

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

        this.state = {
            productTypes: [],
            loadingProductTypes: false,
            loadProductTypeList: this.loadProductTypeList
        };
    }

    loadProductTypeList = (forceLoad = false) => {
        if(true !== this.state.loadingProductTypes || forceLoad) {

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

            (new ApiRequest('api', GET, 'shop/product-types'))
                .debug(true)
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        this.setState({
                            productTypes: res.data,
                            loadingProductTypes: true
                        });
                    } else {
                        this.setState({
                            loadingProductTypes: 'error'
                        });
                    }
                })
                .catch((err) => {
                    this.props.handleApiFail(err, 'listing ProductTypes');
                    if(err && !err.cancelled) {
                        this.setState({
                            loadingProductTypes: 'error'
                        });
                    }
                });
        }
    };

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

const StoreProductTypeProvider = cancelPromise(withApiControl(StoreProductTypeProviderBase));

const storeProductType = withContextConsumer(StoreProductTypeContext.Consumer);

export {StoreProductTypeProvider, storeProductType};