// Lib
import React, {Component} from 'react';
import Group from './Group';
import ContentStore from '../ContentStore';

class SchemaEditor extends Component {

    state = {
        list: null
    };

    constructor(props) {
        super(props);

        this.contentStore = new ContentStore();
    }

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

        if(data && schema && schema.properties && cacheid) {
            // create the sub schema from all defined properties in this schema
            let schema_props = schema.properties;
            delete schema_props._schema;

            let List = [];
            for(let key in schema_props) {
                // create groups for all properties in current schema
                if(schema_props.hasOwnProperty(key)) {
                    List.push(<Group
                        key={key}
                        uid={key}
                        name={key}
                        data={data[key]}
                        schema={schema_props[key]}
                        t={t}
                        contentStore={this.contentStore}
                    />);
                }
            }

            this.setState({
                list: () => List
            });
        } else {
            if(!cacheid) {
                console.error('SchemaEditor: error, no cacheid specified, supply an unique identifier for the current applied data');
            }
        }
    }

    componentDidUpdate(prevProps) {
        if(
            prevProps.cacheid !== this.props.cacheid ||
            prevProps.schema !== this.props.schema
        ) {
            this.setState({
                list: null
            });
            this.createList();
        }
    }

    componentWillUnmount() {
        if(this.props.rmSave) {
            this.props.rmSave();
        }

        this.contentStore.clear();
    }

    componentDidMount() {
        this.createList();

        if(this.props.addSave) {
            this.props.addSave(this.contentStore.save);
        }
    }

    render() {
        if(this.state.list) {
            return <this.state.list/>;
        } else {
            return null
        }
    }
}

export default SchemaEditor;