context = window
teacherActions = window.JK.Actions.Teacher
logger = context.JK.logger
rest = window.JK.Rest()

@TeacherSetupPricing = React.createClass({
  mixins: [
    @TeacherSetupMixin,
    Reflux.listenTo(@AppStore,"onAppInit"),
    Reflux.listenTo(TeacherStore, "onTeacherStateChanged")
  ]

  iCheckIgnore: false
  componentDidUnmount: () ->
    @root.off("change", ".checkbox-enabler")

  componentDidMount: () ->
    @root = jQuery(this.getDOMNode())
    @enableCheckBoxTargets()
    @updateCheckboxState()

  getInitialState: () ->
    {}

  componentDidUpdate: () ->
    @updateCheckboxState()
    @updateSingleCheckbox('teaches_test_drive', @state.teaches_test_drive)
    @enableCheckBoxTargets()


  updateCheckboxState: () ->
    for minutes in [30, 45, 60, 90, 120]
      priceKey = "lesson_duration_#{minutes}"
      enabled = @state[priceKey]
      @updateSingleCheckbox(priceKey, enabled)

  updateSingleCheckbox: (priceKey, enabled) ->
    containerName = ".#{priceKey}_container input[type='checkbox']"
    @iCheckIgnore = true
    if enabled
      @root.find(containerName).iCheck('check').attr('checked', true);
    else
      @root.find(containerName).iCheck('uncheck').attr('checked', false);
    @iCheckIgnore = false

  enableCheckBoxTargets: (e) ->
    checkboxes = @root.find('input[type="checkbox"]')
    context.JK.checkbox(checkboxes)
    checkboxes.on('ifChanged', (e)=> @checkboxChanged(e))
    true

  checkboxChanged: (e) ->
    if @iCheckIgnore
      return
    checkbox = $(e.target)
    name = checkbox.attr('name')
    checked = checkbox.is(':checked')
    this.setState({"#{e.target.name}": e.target.checked})


  screenName: () ->
    "pricing"

  onTeacherStateChanged: (changes) ->

    unless this.handleErrors(changes)
      teacher = changes.teacher
      this.setState({
        price_per_lesson_30_cents: teacher.price_per_lesson_30_cents
        price_per_lesson_45_cents: teacher.price_per_lesson_45_cents
        price_per_lesson_60_cents: teacher.price_per_lesson_60_cents
        price_per_lesson_90_cents: teacher.price_per_lesson_90_cents
        price_per_lesson_120_cents: teacher.price_per_lesson_120_cents
        price_per_month_30_cents: teacher.price_per_month_30_cents
        price_per_month_45_cents: teacher.price_per_month_45_cents
        price_per_month_60_cents: teacher.price_per_month_60_cents
        price_per_month_90_cents: teacher.price_per_month_90_cents
        price_per_month_120_cents: teacher.price_per_month_120_cents
        prices_per_lesson: teacher.prices_per_lesson
        prices_per_month: teacher.prices_per_month
        lesson_duration_30: teacher.lesson_duration_30
        lesson_duration_45: teacher.lesson_duration_45
        lesson_duration_60: teacher.lesson_duration_60
        lesson_duration_90: teacher.lesson_duration_90
        lesson_duration_120: teacher.lesson_duration_120
        test_drives_per_week: teacher.test_drives_per_week,
        teaches_test_drive: teacher.teaches_test_drive
      })
      false



  captureFormState: (e) ->
    this.setState({
      prices_per_lesson:   $("[name='prices_per_lesson_input']", @root).is(":checked")
      prices_per_month:  $("[name='prices_per_month_input']", @root).is(":checked")
      lesson_duration_30: $("[name='lesson_duration_30_input']", @root).is(":checked")
      lesson_duration_45: $("[name='lesson_duration_45_input']", @root).is(":checked")
      lesson_duration_60: $("[name='lesson_duration_60_input']", @root).is(":checked")
      lesson_duration_90: $("[name='lesson_duration_90_input']", @root).is(":checked")
      lesson_duration_120: $("[name='lesson_duration_120_input']", @root).is(":checked")
    })

    #this.forceUpdate()

  captureCurrency: (e) ->
    for minutes in [30, 45, 60, 90, 120]
      lessonValue = $("[name='price_per_lesson_#{minutes}_cents']", @root).val()
      monthlyValue = $("[name='price_per_month_#{minutes}_cents']", @root).val()


      pricePerLessonCents = context.JK.ProfileUtils.normalizeMoneyForSubmit(lessonValue)
      pricePerMonthCents = context.JK.ProfileUtils.normalizeMoneyForSubmit(monthlyValue)


      this.setState({
        "price_per_lesson_#{minutes}_cents": pricePerLessonCents
        "price_per_month_#{minutes}_cents": pricePerMonthCents
      })

      displayLessonAmount = context.JK.ProfileUtils.normalizeMoneyForDisplay(pricePerLessonCents)
      displayMonthAmount = context.JK.ProfileUtils.normalizeMoneyForDisplay(pricePerMonthCents)
      #$("[name='price_per_lesson_#{minutes}_cents']", @root).val(displayLessonAmount)
      #$("[name='price_per_month_#{minutes}_cents']", @root).val(displayMonthAmount)

  navDestination: (instructions) ->
    navTo=null
    if instructions?
      if instructions.direction=="cancel"
        navTo = @teacherSetupSource()
      else if instructions.direction=="back"
        navTo = @teacherSetupDestination("experience")
      else if instructions.direction=="next"

        # prevent any action if the user has unselected teach test drive...
        if !this.state.teaches_test_drive
          @setState({teaches_test_drive: true})
          context.JK.Banner.showAlert('Test Drive Participation Required', "In order to participate in the JamClass online music lesson marketplace by JamKazam, you must be willing to teach at least 10 TestDrive classes per week, ideally more if you want to attract more new students. <br/><br/>TestDrive is the primary means by which JamKazam connects new students to teachers, so if you don't do this, the marketplace will really not help you. <br /><br />If you feel that you have a compelling reason not to give TestDrive lessons, but still want to participate in our marketplace, then please send us an email at support@jamkazam.com to chat with us about it.")

          navTo = 'rejected'
        else
          # We are done:
          navTo = @teacherSetupSource()

    navTo

  handleNav: (e) ->
    navTo = this.navDestination(e)

    if navTo == 'rejected'
      # do nothing...handled elsewhere
    else
      teacherActions.change.trigger(this.state, {navTo: navTo, instructions:e})

  handleFocus: (e) ->
    @pricePerLessonCents=e.target.value

  handleTextChange: (e) ->
    @pricePerLessonCents=e.target.value
    this.forceUpdate()

  handleCheckChange: (e) ->
    if @iCheckIgnore
      return
    this.setState({"#{e.target.name}": e.target.checked})

  handleTestDriveCountChange: (e) ->
    $this = $(e.target)
    value = $this.val()
    this.setState({test_drives_per_week: new Number(value)})

  handleLearnMoreAboutTestDrive: (e) ->
    e.preventDefault()
    alert("Help documentation coming soon!")

  render: () ->
    priceRows = []
    for minutes in [30, 45, 60, 90, 120]
      pricePerLessonName = "price_per_lesson_#{minutes}_cents"
      pricePerMonthName = "price_per_month_#{minutes}_cents"
      priceKey = "lesson_duration_#{minutes}"
      inputName = "#{priceKey}_input"
      containerName = "#{priceKey}_container"
      durationChecked = this.state[priceKey]

      # If we are currently editing, don't format; used cache value:
      if $("[name='#{pricePerLessonName}']", @root).is(":focus")
        pricePerLessonCents = @pricePerLessonCents
      else
        ppl_fld_name="price_per_lesson_"+minutes+"_cents"
        pricePerLessonCents = context.JK.ProfileUtils.normalizeMoneyForDisplay(this.state[ppl_fld_name])


      # If we are currently editing, don't format; used cache value:
      if $("[name='#{pricePerMonthName}']", @root).is(":focus")
        pricePerMonthCents = @pricePerMonthCents
      else
        pricePerMonthCents = context.JK.ProfileUtils.normalizeMoneyForDisplay(this.state["price_per_month_"+minutes+"_cents"])

      pricesPerLessonEnabled  = this.state.prices_per_lesson
      pricesPerMonthEnabled   = this.state.prices_per_month

      monthlyEnabled = durationChecked && pricesPerMonthEnabled
      lessonEnabled = durationChecked && pricesPerLessonEnabled
      perMonthInputStyles = classNames({"per-month-target" : true, disabled: !monthlyEnabled})
      perLessonInputStyles = classNames({"per-lesson-target": true, disabled: !lessonEnabled})

      test_drive_lessons = []
      for i in [2..10]
        test_drive_lessons.push(`<option value={i} key={i}>{i}</option>`)

      priceRows.push `
        <div className="teacher-price-row" key={minutes}>
          <div className="teacher-half-column left pricing-options">
            <div className="teacher-field" name={containerName}>
              <input type='checkbox'
                      className={"checkbox-enabler " + priceKey}
                      data-enable-target={"lesson-"+minutes+"-target"}
                      name={priceKey}
                      key={priceKey}
                      checked={this.state[priceKey]}
                      onChange={this.handleCheckChange}
                      ref={priceKey}>
              </input>
              <label htmlFor='{priceKey}' key='{priceKey}' className="checkbox-label">
                {minutes} Minutes
              </label>
            </div>
          </div>

          <div className="teacher-half-column right pricing-amounts">
            <div className={"teacher-field pricing-field month-"+minutes+"-target"}>
              <div className="teacher-third-column minute-label inline">
                <label>{minutes} Minutes</label>
              </div>
              <div className="teacher-third-column inline per-lesson">
                <span className="money-type">$</span><input key={minutes}
                       name={pricePerLessonName}
                       ref={pricePerLessonName}
                       className={perLessonInputStyles}
                       type="text"
                       min="0"
                       max="100000"
                       value={pricePerLessonCents}
                       onBlur={this.captureCurrency}
                       onChange={this.handleTextChange}
                       onFocus={this.handleFocus}
                       disabled={!lessonEnabled}>
                </input>
              </div>
              <div className="teacher-third-column inline per-month">
                <span className="money-type">$</span><input key={minutes}
                       name={pricePerMonthName}
                       ref={pricePerMonthName}
                       className={perMonthInputStyles}
                       type="text"
                       min="0"
                       max="100000"
                       value={pricePerMonthCents}
                       onBlur={this.captureCurrency}
                       onChange={this.handleTextChange}
                       onFocus={this.handleFocus}
                       disabled={!monthlyEnabled}>
                </input>
              </div>
            </div>
          </div>
          <br className="clearall"/>
        </div>`

    # Render:
    `<div className="TeacherSetupPricing TeacherSetupComponent" >
      <div className="teacher-half-column left pricing-options">
        <h3 className="margined">Offer Lessons Pricing & Payments:</h3>

        <div className="teacher-field" name="prices_per_lesson_container">
          <input type='checkbox' className='checkbox-enabler' data-enable-target="per-lesson-target" name="prices_per_lesson" checked={this.state.prices_per_lesson} ref="prices_per_lesson" onChange={this.handleCheckChange}></input>
          <label htmlFor='prices_per_lesson' className="checkbox-label">Per Lesson</label>
        </div>

        <div className="teacher-field" name="prices_per_month_container">
          <input type='checkbox' className='checkbox-enabler' data-enable-target="per-month-target" name="prices_per_month" checked={this.state.prices_per_month} ref="prices_per_month" onChange={this.handleCheckChange}></input>
          <label htmlFor='prices_per_month' className="checkbox-label">Per Month</label>
        </div>

      </div>

      <div className="teacher-half-column right pricing-amounts">
        <h3 className="margined pricing-amount-text-prompt">Please fill in the prices (in US Dollars) for the lessons you have chosen to offer in the boxes below:</h3>
      </div>
      <br className="clearall"/>

      <div className="teacher-price-row">
        <div className="teacher-half-column left pricing-options">
          <h3 className="margined">Offer Lessons of These Durations:</h3>
        </div>
        <div className="teacher-half-column right pricing-amounts">
            <div className="teacher-third-column">&nbsp;</div>
            <div className="teacher-third-column">
              <h3 className="margined">Price Per Lesson</h3>
            </div>
            <div className="teacher-third-column">
              <h3 className="margined">Price Per Month</h3>
            </div>
        </div>
        <br className="clearall"/>
      </div>

      {priceRows}

      <div className="teacher-price-row">
        <h3 className="margined">TestDrive Program:</h3>

        <div className="teacher-field teaches_test_drive_container">
          <input type='checkbox' className='checkbox-enabler' name="teaches_test_drive" checked={this.state.teaches_test_drive} ref="teaches_test_drive" onChange={this.handleCheckChange}></input>
          <label htmlFor='test_drives_per_week' className="checkbox-label">I agree to teach up to
            <select name="test_drives_per_week" className="test_drives_per_week" value={this.state.test_drives_per_week} onChange={this.handleTestDriveCountChange}>{test_drive_lessons}</select>
            TestDrive lessons per week</label>
          <div className="test-drive-explain">
            TestDrive is the primary marketing program JamKazam uses to drive new students through our marketplace to teachers. You will be paid $10 per 30-minute TestDrive lesson that you teach. Teach more TestDrive lessons to acquire more students.
          </div>
        </div>
      </div>

      <br className="clearall"/>
      <TeacherSetupNav handleNav={this.handleNav} last={true}></TeacherSetupNav>
    </div>`


})