context = window
rest = window.JK.Rest()
logger = context.JK.logger

@TeacherExperienceEditableList = React.createClass({
  componentDidUnmount: () ->
    @root.off("submit", ".teacher-experience-teaching-form")

  componentDidMount: () ->
    @root = jQuery(this.getDOMNode())
    @root.off("submit", ".teacher-experience-teaching-form")#.on("submit", ".teacher-experience-teaching-form", @addExperience)

  formatListItem: (obj) ->

    if obj.end_year?
      endYear = obj.end_year

      if endYear == '0' || endYear == 0
        endYear = 'Now'
    else
      endYear = 'Now'

    t = "#{obj.name}/#{obj.organization} (#{obj.start_year}"
    t += "-#{endYear}" if this.props.showEndDate
    t += ")"

  getInitialProps: () ->
    {listItems: []}

  sortListItems: () ->
    this.props.listItems ||= []
    this.props.listItems = _.sortBy(this.props.listItems, 'start_year')

  addExperience: (e) ->
    e.preventDefault()
    $form = @root.find('.teacher-experience-teaching-form')

    start_year = parseInt($("[name='start_year']", $form).val())
    end_year = parseInt($("[name='end_year']", $form).val())

    console.log("end_yeaor", end_year)
    if this.props.showEndDate && end_year != 0 && start_year > end_year
      this.setState({errors: ["End year must be greater than start year"]})
    else
      this.props.listItems.push {
        name: $("[name='title_input']", $form).val()
        organization: $("[name='organization_input']", $form).val()
        start_year: start_year
        end_year: end_year
      }
      logger.debug("addExperience", this.props.listItems)
      this.props.onItemChanged(this.props.experienceType, this.props.listItems)
      #$form.reset()
      this.setState({errors: null})

  getInitialState: () ->
    {errors:null}

  onItemChanged: (listName, listObjects) ->
    this.setState({errors: null})
    this.props.onItemChanged(listName, listObjects)

  render: () ->
    endDate = []
    if this.props.showEndDate
      endDate.push `<span key={"end_date"} ><label htmlFor="end-year">to</label>
                    <YearSelect name="end_year" defaultPresent={true}></YearSelect></span>`
      dtLabel = "Start & End"
    else
      dtLabel = "Date"

    titleLabel = this.props.titleLabel
    orgLabel = this.props.orgLabel

    titleLabel ||= "Title"
    orgLabel ||= "School/Org"

    listItems= _.sortBy(this.props.listItems, 'start_year')
    errorClasses = classNames({hidden: !@state.error?, "error-text": true})

    errors = []
    if this.state.errors?
      for error in this.state.errors
        errors.push(`<span key={error}>{error}</span>`)

    `<div className="TeacherExperienceEditableList react-component">
      <form className="teacher-experience-teaching-form">
        <div className="form-table">
            <div className="teacher-field title">
              <label htmlFor="title-input">{titleLabel}:</label>
              <input type="text" name="title_input" required="required"> </input>
            </div>
            <div className="teacher-field organization">
              <label htmlFor="organization-input">{orgLabel}:</label>
              <input type="text" name="organization_input" required="required"> </input>
            </div>
            <div className="teacher-field date">
              <label htmlFor="start-year">{dtLabel}:</label>
              <span className="year-range-cell">
                  <YearSelect name="start_year"> </YearSelect>
                  {endDate}
              </span>
            </div>
        </div>
        <button className="add-experience-btn button-grey right" type="submit" onClick={this.addExperience}>ADD</button>
      </form>
      <EditableList objectName={this.props.experienceType} onItemChanged={this.onItemChanged} listItems={listItems} formatListItem={this.formatListItem}/>
      <div className={errorClasses}>
        {errors}
      </div>
    </div>`
})