import React from 'react';
import Form from "@rjsf/bootstrap-4";
import { IJsonSchema } from '../../types/IJSONSchema'
import { Button } from 'react-bootstrap';

export interface DynamicFormProps<T> {
    schema: IJsonSchema,
    data?: any
    uiSchema?: any,
    onCancel: (err: any) => Promise<void>;
    onSubmit: (data: T) => Promise<void>;
}

export interface DynamicFormState<T> {
}

/**
 * Uses: 
 * https://react-jsonschema-form.readthedocs.io/en/latest/
 */
class DynamicForm<T = any> extends React.Component<DynamicFormProps<T>, DynamicFormState<T>> {

    constructor(props) {
        super(props);
    }

    _submitButtonPressed(data: any){
        if (typeof this.props.onSubmit == "function"){
            this.props.onSubmit(data as T);
        }
    }

    _cancelButtonPressed(){
        if (typeof this.props.onCancel == "function"){
            this.props.onCancel(new Error("Input Canceled"));
        }
    }


    public render() {
        return (
            <Form schema={this.props.schema as any} uiSchema={this.props.uiSchema} formData={this.props.data} liveValidate onSubmit={e => this._submitButtonPressed(e.formData)}>
                <Button type="submit" variant="success">Submit</Button>{' '}
                <Button variant="danger" onClick={_ =>this._cancelButtonPressed()}>Cancel</Button>{' '}
            </Form>
        );
    }
}

export default DynamicForm;