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

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

        this.state = {
            sections: [],
            loadingSections: false,
            loadSectionList: this.loadSectionList
        };
    }

    loadSectionList = (forceLoad = false) => {
        if(true !== this.state.loadingSections || forceLoad) {

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

            (new ApiRequest('api', GET, 'content/section'))
                .debug(true)
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        this.setState({
                            sections: res.data,
                            loadingSections: true
                        });
                    } else {
                        this.setState({
                            loadingSections: 'error'
                        });
                    }
                })
                .catch((err) => {
                    this.props.handleApiFail(err, 'listing Sections');
                    if(err && !err.cancelled) {
                        this.setState({
                            loadingSections: 'error'
                        });
                    }
                });
        }
    };

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

const StoreSectionProvider = cancelPromise(withApiControl(StoreSectionProviderBase));

const storeSection = withContextConsumer(StoreSectionContext.Consumer);

export {StoreSectionProvider, storeSection};