import React from 'react';
import ReactDom from 'react-dom';
import Select from 'react-select';

//Get the registerBlockType() function used for the registration of the block
const {registerBlockType} = wp.blocks;

//Get the base Component used to defined new components
const {Component} = wp.element;

class BlockEdit extends Component {

  constructor(props) {

    super(...arguments);
    this.props = props;
    this.state = {
      chartList: [],
      selectedOption: null,
      placeholder: '',
    };

  }

  /**
   * This method is invoked immediately after a component is mounted (inserted
   * into the tree). Initializations that requires DOM nodes should go here. If
   * you need to load data from a remote endpoint, this is a good place to
   * instantiate the network requests.
   *
   * https://reactjs.org/docs/react-component.html#componentdidmount
   */
  componentDidMount() {

    let {attributes: {chartId}} = this.props;

    let params = 'security=' + dauc_nonce;
    params += '&action=dauc_get_chart_list';

    fetch(dauc_ajax_url, {
      method: "POST",
      credentials: 'include',//Required to avoid the 400 Bad Request error with Edge
      headers: {'Content-type': 'application/x-www-form-urlencoded'},
      body: params,
    })
    .then((response) => {

      if(response.ok) {
        return response.json();
      }else{
        throw new Error('Network response was not ok.');
      }

    })
    .then((data) => {

      //Update the React Select options
      let options = data.map((item) => ({
        value: item.id,
        label: item.name,
      }));
      this.setState({
        chartList: options,
      });

      //Find the selected item
      const selectedItem = options.find(function(item) {
        if(item.value === chartId){
          return item;
        }
      });

      //Set the React Select Placeholder or set the React Select selected option
      if(typeof selectedItem === 'undefined'){
        this.setState({
          placeholder: daucObjectL10n.selectPlaceholder
        });
      }else{
        this.setState({
          selectedOption: {
            value: chartId,
            label: selectedItem.label
          }
        });
      }

    })
    .catch(error => {

      console.log('There has been a problem with your fetch operation: ', error.message);

    });

  }

  render() {

    const {attributes: {chartId}, setAttributes} = this.props;

    return (
        <Select
            classNamePrefix="dauc-react-select"
            value={this.state.selectedOption}
            onChange={( selectedOption ) => {
              setAttributes({chartId: selectedOption.value});
              this.setState({selectedOption});
            }}
            options={this.state.chartList}
            placeholder={this.state.placeholder}
            noOptionsMessage={() => daucObjectL10n.selectNoOptionsMessage}
        />
    );

  }

}

/**
 * Register the Gutenberg block
 */
registerBlockType('dauc/select-chart', {
  // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
  title: 'UberChart', // Block title.
  icon: 'chart-line', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
  category: 'widgets', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
  keywords: [
    daucObjectL10n.chartKeyword,
    daucObjectL10n.graphKeyword,
    daucObjectL10n.diagramKeyword,
  ],
  attributes: {
    chartId: {
      type: 'string',
    },
  },

  /**
   * The edit function describes the structure of your block in the context of the editor.
   * This represents what the editor will render when the block is used.
   *
   * The "edit" property must be a valid function.
   *
   * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
   */
  edit: BlockEdit,

  /**
   * The save function defines the way in which the different attributes should be combined
   * into the final markup, which is then serialized by Gutenberg into post_content.
   *
   * The "save" property must be specified and must be a valid function.
   *
   * @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
   */
  save: function() {

    /**
     * This is a dynamic block and the rendering is performed with PHP:
     *
     * https://wordpress.org/gutenberg/handbook/blocks/creating-dynamic-blocks/
     */
    return null;

  },

});
