import * as React from "react";

import * as ClientModel from './models/form.client.models'
import * as ServerResponse from './models/form.server.models'

import {FormsApiClient} from './forms-client';
import {Section} from "./form-elements/section";
import {FormResult_to_Model} from "./models/form.projections";

export interface UrlProps {
    [index: string]: string;
    formId: string
}
export interface FormProps {
    [index: string]: any;
    jsonDefinition: ClientModel.FormDefinition | null
}
export interface State {
    definition: ClientModel.FormDefinition | null
}

export class Form extends React.Component<UrlProps | FormProps, State> {
    constructor(props: UrlProps | FormProps) {
        super(props);
        this.state = {definition: null}
    }

    // ~todo~ remove this once backend supports sending the full message.
    private static wrapServerResponse(layout: ServerResponse.FormInput[]): ServerResponse.FormDefinition {
        return {
            meta: {
                formId: 'the id',
                instanceId: 'the instance',
                title: "Untitled Form"
            },
            sections: [
                {
                    meta: {
                        sectionId: "the section id",
                        title: "Untitled Section",
                        layout: "simple"
                    },
                    layout
                }
            ]
        };
    }

    async componentDidMount() {
        let {formId} = this.props;
        if (formId) {
            let response: any = await FormsApiClient.Forms
                .Forms_GetFormById({
                    id: formId
                }, {
                    responseContentType: "application/vnd.api+json"
                });
            let {layouts} = response.obj.data.attributes;
            this.setState({
                definition: FormResult_to_Model(Form.wrapServerResponse(layouts)) as ClientModel.FormDefinition
            });
        }
    }

    render() {
        let {jsonDefinition} = this.props;
        var form: ClientModel.FormDefinition = this.state.definition
            ? this.state.definition
            : jsonDefinition;
        if (form) {
            const formTitle = form.meta.title ? <h1 className="form-title">{form.meta.title}</h1> : '';
            const sections = form.sections.map((item, idx) =>
                <Section key={idx} definition={item}/>);
            return <div className="form">
                {formTitle}
                {sections}
            </div>;
        }
        return <div></div>
    }
}