﻿import * as React from 'react'
import { IComponentType } from '../../interfaces'
import { contentTypeResolver } from './ComponentTypesExtender'
import { CustomContentTypeBase } from './CustomTypeBase'

export class ContentTypeResolver extends React.Component<IComponentType, any> {
    control: CustomContentTypeBase | null = null

    constructor (props: IComponentType) {
        super(props)
    }

    validateForm (): boolean {
        if (this.control !== null) {
            if (this.control.customValidate) {
                const isValid = this.control.validateForm()
                if (this.props.setMenuValidity !== undefined) {
                    this.props.setMenuValidity(isValid, this.props.contentMenuItem)
                }
                return isValid
            }

            if (this.control.formik !== null) {
                const formikBag = this.control.formik.getFormikBag()
                if (this.props.setMenuValidity !== undefined) {
                    this.props.setMenuValidity(formikBag.isValid, this.props.contentMenuItem)
                }
                return formikBag.isValid
            }
        }
        return true
    }

    getData (): any {
        if (this.control !== null) {
            if (this.control.customGetData) {
                return this.control.getData()
            }

            if (this.control.formik !== null) {
                void this.control.formik.submitForm()
                return this.control.getData()
            }
        }
        return {}
    }

    submitForm () {
        if (this.control !== null) {
            if (this.control.customSubmitForm !== undefined) {
                this.control.customSubmitForm()
            } else if (this.control.formik !== null) {
                void this.control.formik.submitForm()
            }
        }
    }

    public render () {
        let output: JSX.Element | null = null
        const {
            edit,
            pageType,
            contentData,
            culture,
            contentMenuItem,
            arragroCmsRulesExceptionDto,
            onFormikChange,
            setMenuValidity,
            saveStashedIncomplete
        } = this.props

        const contentType = contentTypeResolver({
            ref: (x: any) => this.control = x,
            edit,
            saving,
            pageType,
            contentData,
            culture,
            contentMenuItem,
            arragroCmsRulesExceptionDto,
            onFormikChange,
            setMenuValidity,
            saveStashedIncomplete
        })

        if (!contentType) {
            output = <div className='validation-error'>
                <div>There is no page component type for {pageType.fullName}.</div>
                <div>This is required please develop and configure a component for this namespaced component!</div>
            </div>
        } else {
            output = contentType
        }

        return output
    }
}
            saving,