import React from 'react';
import {withContextConsumer} from "@formanta/react";
import {ID} from "@formanta/js";

const ErrorControlContext = React.createContext({});

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

        this.state = {
            errors: [],
            addError: this.addError,
            solveError: this.solveError
        };
    }

    addError = (err, details, label = false, fatal = true) => {
        err = {...err};
        const errors = [...this.state.errors];

        err.key = ID();
        err.timestamp = new Date();
        err.details = details;
        err.label = label;
        err.fatal = fatal;
        errors.push(err);
        this.setState({errors})
    };

    solveError = (id) => {
        const errors = [...this.state.errors];
        errors.splice(id, 1);
        this.setState({errors})
    };

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

const withErrorControl = withContextConsumer(ErrorControlContext.Consumer);

export {ErrorControlProvider, withErrorControl};