'use strict';

const e = React.createElement;

class ProgramDropdown extends React.Component {
  constructor(props) {
    super(props);
    var queryParams = getUrlVars();
    var querySelectedProgramOrBlank = (typeof queryParams['program'] != 'undefined') ? queryParams['program'] : '';

    // Sanitized
    querySelectedProgramOrBlank = encodeURIComponent(querySelectedProgramOrBlank);

    this.state = { 
      selectedProgram: querySelectedProgramOrBlank
    };

    // Set initial value in view if we have one.
    if (querySelectedProgramOrBlank != '') {
      this.updateViewForm(querySelectedProgramOrBlank);
    }

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

  handleChange(event) {
    var newVal = event.target.value;
    this.setState({
      selectedProgram: newVal
    });

    this.updateViewForm(newVal);
  }

  updateViewForm(newVal) {
    // Update Affiliated DOM Element
    // & Submit Affiliated Form if applicable
    $(this.props.controlElementSelector).val(newVal);
    var form = $("#edit-field-program-slug-value").parents('form');
    if (form) {
      var submitButton = form.find('.form-submit');
      if (submitButton) {
        submitButton.click();
      }
    }
  }

  render() {
    // Create Select List
    var selectList = null;
    if (this.props.programs && Object.keys(this.props.programs).length) {
      var options = [];
      var programs = this.props.programs;
      var programKeys = Object.keys(programs);
      programKeys.forEach(function(key){
        // console.log(key);
        options.push(
          <option key={'program-'+key} value={key}>
            {programs[key]}
          </option>
        )
      });

      selectList = (
        <select title="Select a Program" value={this.state.selectedProgram} onChange={this.handleChange}>
          <option value=''>Select a Program</option>
          {options}
        </select>
      )
    }

    // Display a "Like" <button>
    return (
      <div className="gse-program-dropdown-display">
        {selectList}
      </div>
    );
  }
}

function getProgramsObject(programLiElements) {
  var programs = {};

  programLiElements.each(function(idx, program){
    var programInfo = program.innerText.split("|");
    if (programInfo.length == 2) {
      var key = programInfo[0].trim();
      if (key && key != "") {
        programs[key] = programInfo[1].trim();
      }
    }
  })

  return programs;
}

// Read a page's GET URL variables and return them as an associative array.
// http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

var domContainer = document.querySelector('.gse-program-dropdown');
if (domContainer) {
  var programLiElements = $(domContainer).find('li');
  var programs = getProgramsObject(programLiElements);
  var controlElementSelector = $(domContainer).attr('aria-controls') ? $(domContainer).attr('aria-controls') : null;

  // Class controls-[ID SELECTOR] Method Instead of aria-controls.
  if (!controlElementSelector) {
    var classes= $(domContainer).attr('class');
    if (classes) {
      var classList = classes.split(" ");
      for (var i = 0; i < classList.length; i++) {
        if (classList[i].substr(0,9) == 'controls-') {
          controlElementSelector = '#' + classList[i].substr(9);
        }
      }
    }
  }

  // If this is a view, do the react component on the inner content
  // this way we can keep the view-header and view-footer if needed.
  if ($(domContainer).hasClass('view')) {
    domContainer = $(domContainer).find('.view-content')[0];
  }

  // console.log(programs);
  ReactDOM.render(
    <ProgramDropdown
      programs={programs}
      controlElementSelector={controlElementSelector}>
    </ProgramDropdown>, 
    domContainer
  );
}
