import React, {Component} from 'react';

import Loadable from 'react-loadable';
import Loading from '../../component/Loading';

const factory = {
    'string': Loadable({
        loader: () => import('./field/String'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/String'/>,
    }),
    'StringList': Loadable({
        loader: () => import('./field/StringList'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/StringList'/>,
    }),
    'GenericList': Loadable({
        loader: () => import('./field/GenericList'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/GenericList'/>,
    }),
    'TextRich': Loadable({
        loader: () => import('./field/TextRich'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/TextRich'/>,
    }),
    'TextRichInline': Loadable({
        loader: () => import('./field/TextRichInline'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/TextRichInline'/>,
    }),
    'File': Loadable({
        loader: () => import('./field/File'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/File'/>,
    }),
    'Files': Loadable({
        loader: () => import('./field/Files'),
        loading: (props) => <Loading {...props} name='SchemaEditor/field/Files'/>,
    }),
};

class SchemaField extends Component {

    constructor(props) {
        super(props);

        const {schema, uid, name, contentStore} = this.props;

        this.contentStore = false;
        if(contentStore) {
            this.contentStore = contentStore.createItem(uid);
        } else {
            console.error('SchemaField: error, no contentStore supplied for ' + name);
        }

        this.comp = false;

        if(schema) {
            if(factory.hasOwnProperty(schema.type)) {
                this.comp = factory[schema.type];
            }
        } else {
            console.error('SchemaField, tried to create field without registered schema.type: `' + schema.type + '` in `' + name + '`.');
        }
    }

    render() {
        const {t, data, schema} = this.props;

        return (
            this.comp ?
                <this.comp
                    name={this.props.name}
                    t={t}
                    data={data}
                    schema={schema}
                    {...this.contentStore}
                /> :
                null);
    };
}

export default SchemaField;