import {
    IField, IFieldEnum, IFieldGroup, IFieldList
} from '@wowpic/xform-types';
import React, { FunctionComponent } from 'react';
import Field from './field';
import FieldGroup from './fieldGroup';
import FieldList from './fieldList';

const Switcher: FunctionComponent<any> = ({ core, fields }) => {
    const renderField = (field: IFieldEnum) => {
        if (field.type === 'Array') {
            return (
                <FieldList
                    key={field.key}
                    core={core}
                    field={field as IFieldList} />
            );
        }
        if (field.type === 'Object') {
            return (
                <FieldGroup
                    key={field.key}
                    core={core}
                    field={field as IFieldGroup} />
            );
        }
        return (
            <Field
                key={field.key}
                core={core}
                field={field as IField} />
        );
    };

    const groupMap: any = {};
    const results = fields.reduce((result: any[], field: IFieldEnum) => {
        const groupname = field.ui && field.ui.groupname;
        if (groupname) {
            if (!groupMap[groupname]) {
                result.push(groupname);
                groupMap[groupname] = [];
            }
            groupMap[groupname].push(field);
        } else {
            result.push(field);
        }
        return result;
    }, []);

    if (Object.keys(groupMap).length > 0) {
        return (
            <>
                {results.map((item: any) => {
                    if (typeof item === 'string') {
                        const groupname = item;
                        return (
                            <div className={groupname} key={groupname}>
                                {groupMap[groupname].map((field: IFieldEnum) => renderField(field))}
                            </div>
                        );
                    }
                    return renderField(item as IFieldEnum);
                })}
            </>
        );
    }

    return (
        <>
            {fields.map((field: IFieldEnum) => renderField(field))}
        </>
    );
};

export default Switcher;
