import * as React from 'react';
import * as _ from 'lodash';
import {BasicContainerPropsInterface, BasicConfig} from '../core/Container/types';
import componentLoader from '../util/componentLoader';
import Trigger from '../core/Trigger/Trigger';
import Form from '../core/Form/Form';
import '../../components/index';
import '../core/Layout/Row/Row';

export function createChild<T extends BasicConfig, P extends BasicContainerPropsInterface>
(info: T, childProps: P, childElements: React.ReactNode = null): React.ReactNode {
    if (!_.isPlainObject(info)) {
        console.error('invalid Info Object', info);
        return React.createElement('div', {}, 'invalid Item Object');
    }

    let component: React.ComponentClass<any>;
    // let componentInterface;

    let componentInfo;

    try {
        componentInfo = componentLoader.getComponent(info.type);
    } catch (e) {
        console.error(e);
        return <div className="rcre-error">{e.message}</div>;
    }

    if (!componentInfo || !componentInfo.component) {
        return React.createElement('pre', {}, `can not find component of type ${info.type}`);
    }

    component = componentInfo.component;
    // componentInterface = componentInfo.componentInterface;

    let children: React.ReactNode = React.createElement(component, childProps, childElements);

    if (info.type === 'form') {
        children = (
            <Form
                {...childProps}
            >
                {children}
            </Form>
        );
    }

    if (info.trigger) {
        children = (
            <Trigger
                {...childProps}
                info={childProps.info!}
                $data={childProps.$data!}
                $setData={childProps.$setData!}
                model={childProps.model!}
                dataCustomer={childProps.dataCustomer!}
                key={childProps.key!}
            >
                {children}
            </Trigger>
        );
    }

    return children;
}
