import React from 'react';
import Accordion from '../../shared/Accordion';
import FieldText from '../../entry/fields/Text';
import FieldTextArea from '../../entry/fields/Textarea';
import FieldRichText from '../../entry/fields/Richtext';
import FieldSelect from '../../entry/fields/Select';
import FieldFile from '../../entry/fields/File';

class Settings extends React.Component {
  constructor(props) {
    super(props);

    this.state = props.settings;
  }

  getFieldComponent(type) {
    const map = {
      text: FieldText,
      textarea: FieldTextArea,
      richtext: FieldRichText,
      select: FieldSelect,
      file: FieldFile,
    };

    if (!map.hasOwnProperty(type)) {
      throw new Error(`Invalid field type: ${type}`);
    }

    return map[type];
  }

  renderFields() {
    const { fields } = this.props.info;

    return Object.entries(fields)
      .map(([name, field]) => this.renderField(name, field));
  }

  renderField(name, field) {
    const Component = this.getFieldComponent(field.type);

    return <Component value={this.state[name] || ''}
      title={field.label}
      name={name}
      key={`settings-${name}`}
      desc={field.desc}
      onChange={this.props.onChange} />
  }

  render() {
    const { title, desc } = this.props.info;

    return (
      <Accordion title={title} desc={desc}>
        {this.renderFields()}
      </Accordion>
    )
  }
}

export default Settings;
