import React from 'react';
import FieldRepeater from '../../entry/fields/Repeater';
import MenuItem from './MenuItem';

class Menu extends React.Component {
  state = {};

  constructor(props) {
    super(props);

    try {
      this.state.items = JSON.parse(props.items);
    } catch (e) {
      this.state.items = [];
    }

    this.handleMenuItemChange = this.handleMenuItemChange.bind(this);
  }

  handleMenuItemChange(index, item) {
    this.setState(state => {
      state.items[index] = item;

      return state;
    }, () => {
      this.props.onChange(
        this.props.name,
        JSON.stringify(this.state.items)
      );
    });
  }

  renderRows() {
    return this.state.items.map((item) => {
      return <MenuItem item={item} onChange={this.handleMenuItemChange} />;
    });
  }

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

    return (
      <div className="box box-card">
        <FieldRepeater title={title} desc={desc} rows={this.renderRows()}>
          <MenuItem onChange={this.handleMenuItemChange} />
        </FieldRepeater>
      </div>
    )
  }
}

export default Menu;
