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

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

        this.state = {
            schemas: {},
            loadingSchema: {},
            loadSchema: this.loadSchema,
            isSchemaLoaded: this.isSchemaLoaded
        };
    }

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

    updateSchemaLoaded = (section, status) => {
        const loadingSchema = {...this.state.loadingSchema};
        loadingSchema[section] = status;
        this.setState({loadingSchema});
    };

    loadSchema = (schema, forceLoad = false) => {
        if((isUndefined(this.state.schemas[schema]) && false === this.isSchemaLoaded(schema)) || forceLoad) {

            this.updateSchemaLoaded(schema, 'progress');
            (new ApiRequest('api', GET, 'content/schema/' + schema))
                .debug(true)
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        const schemas = {...this.state.schemas};
                        schemas[schema] = res.data;

                        this.setState({
                            schemas,
                        });
                        this.updateSchemaLoaded(schema, true);
                    } else {
                        this.updateSchemaLoaded(schema, 'error');
                    }
                })
                .catch((err) => {
                    this.props.handleApiFail(err, 'loading Schema');
                    if(err && !err.cancelled) {
                        this.updateSchemaLoaded(schema, 'error');
                    }
                });
        }
    };

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

const StoreSchemaProvider = cancelPromise(withApiControl(StoreSchemaProviderBase));

const storeSchema = withContextConsumer(StoreSchemaContext.Consumer);

export {StoreSchemaProvider, storeSchema};