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

const StorePageTypeContext = React.createContext({});

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

        this.state = {
            pageTypes: {},
            loadingPageType: {},
            loadPageType: this.loadPageType,
            isPageTypeLoaded: this.isPageTypeLoaded
        };
    }

    isPageTypeLoaded = (section) => {
        if(isUndefined(this.state.loadingPageType[section])) {
            return false;
        }
        return this.state.loadingPageType[section];
    };

    updatePageTypeLoaded = (page_type, status) => {
        const loadingPageType = {...this.state.loadingPageType};
        loadingPageType[page_type] = status;
        this.setState({loadingPageType});
    };

    loadPageType = (pageType, forceLoad = false) => {
        if((!isUndefined(this.state.pageTypes[pageType]) && true === this.isPageTypeLoaded(pageType)) && !forceLoad) {
            return Promise.resolve(this.state.pageTypes[pageType]);
        } else if((isUndefined(this.state.pageTypes[pageType]) && false === this.isPageTypeLoaded(pageType)) || forceLoad) {

            this.updatePageTypeLoaded(pageType, 'progress');
            return (new ApiRequest('api', GET, 'content/page-type/' + pageType))
                .debug(true)
                .header({})
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        const pageTypes = {...this.state.pageTypes};
                        pageTypes[pageType] = res.data;

                        this.setState({
                            pageTypes,
                        });
                        this.updatePageTypeLoaded(pageType, true);

                        return res.data;
                    } else {
                        this.updatePageTypeLoaded(pageType, 'error');
                    }
                    return Promise.reject();
                })
                .catch((err) => {
                    this.props.handleApiFail(err, 'loading PageType');
                    if(err && !err.cancelled) {
                        this.updatePageTypeLoaded(pageType, 'error');
                    }
                    return Promise.reject();
                });
        } else if('progress' === this.isPageTypeLoaded(pageType)) {
            return Promise.reject({waitForPageType: true})
        } else {
            return Promise.reject();
        }
    };

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

const StorePageTypeProvider = cancelPromise(withApiControl(StorePageTypeProviderBase));

const storePageType = withContextConsumer(StorePageTypeContext.Consumer);

export {StorePageTypeProvider, storePageType};