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 StoreGroupContext = React.createContext({});

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

        this.state = {
            groups: [],
            loadingGroups: false,
            loadGroupList: this.loadGroupList
        };
    }

    loadGroupList = (forceLoad = false) => {
        if(true !== this.state.loadingGroups || forceLoad) {

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

            (new ApiRequest('api', GET, 'shop/group'))
                .debug(true)
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        this.setState({
                            groups: res.data,
                            loadingGroups: true
                        });
                    } else {
                        this.setState({
                            loadingGroups: 'error'
                        });
                    }
                })
                .catch((err) => {
                    this.props.handleApiFail(err, 'listing Groups');
                    if(err && !err.cancelled) {
                        this.setState({
                            loadingGroups: 'error'
                        });
                    }
                });
        }
    };

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

const StoreGroupProvider = cancelPromise(withApiControl(StoreGroupProviderBase));

const storeGroup = withContextConsumer(StoreGroupContext.Consumer);

export {StoreGroupProvider, storeGroup};