context = window
SchoolStore = context.SchoolStore

@InviteSchoolUserDialog = React.createClass({

  mixins: [Reflux.listenTo(@AppStore, "onAppInit"), Reflux.listenTo(SchoolStore, "onSchoolChanged")]
  teacher: false

  beforeShow: (args) ->
    logger.debug("InviteSchoolUserDialog.beforeShow", args.d1)
    @firstName = ''
    @lastName = ''
    @email = ''

    @setState({inviteErrors: null, teacher: args.d1})
  afterHide: () ->

  onSchoolChanged: (schoolState) ->
    @setState(schoolState)

  onAppInit: (@app) ->
    dialogBindings = {
      'beforeShow': @beforeShow,
      'afterHide': @afterHide
    };

    @app.bindDialog('invite-school-user', dialogBindings);

  componentDidMount: () ->
    @root = $(@getDOMNode())

  getInitialState: () ->
    {inviteErrors: null, school: null, sending: false}

  doCancel: (e) ->
    e.preventDefault()
    @app.layout.closeDialog('invite-school-user', true);

  doInvite: (e) ->
    e.preventDefault()

    if this.state.sending
      console.log("sending already")
      return

    email = @root.find('input[name="email"]').val()
    lastName = @root.find('input[name="last_name"]').val()
    firstName = @root.find('input[name="first_name"]').val()
    school = context.SchoolStore.getState().school
    @setState({inviteErrors: null, sending: true})
    rest.createSchoolInvitation({
      id: school.id,
      as_teacher: this.state.teacher,
      email: email,
      last_name: lastName,
      first_name: firstName
    }).done((response) => @createDone(response)).fail((jqXHR) => @createFail(jqXHR))

  createDone: (response) ->
    console.log("invitation added", response)
    @setState({inviteErrors:null, sending: false})
    context.SchoolActions.addInvitation(this.state.teacher, response)
    context.JK.Banner.showNotice("invitation sent", "Your invitation has been sent!")
    @app.layout.closeDialog('invite-school-user')

  createFail: (jqXHR) ->
    handled = false

    if jqXHR.status == 422
      errors = JSON.parse(jqXHR.responseText)
      @setState({inviteErrors: errors, sending: false})
      handled = true

    if !handled
      @app.ajaxError(jqXHR, null, null)

  renderEducation: () ->
    `<div>
      <div className="content-head">
        <img className="content-icon" src="/assets/content/icon_add.png" height={19} width={19}/>

        <h1>How to Invite Your Students</h1>
      </div>
      <div className="dialog-inner">

        <p>
          Please copy and paste the text below into the email application you use to communicate with students and
          parents in your music program. This is a suggested starting point, but you may edit the message as you prefer.
          Please make sure the web page link in this message is included in the email you send and is unchanged because
          students must use this specific link to sign up so that they will be properly associated with your school.
        </p>
        <textarea readonly="true" value={this.educationCopyEmailText()}></textarea>


        <div className="actions">
          <a onClick={this.close} className="button-orange">DONE</a>
        </div>
      </div>
    </div>`

  close: (e) ->
    e.preventDefault()
    @app.layout.closeDialog('invite-school-user');

  educationCopyEmailText: () ->
    path = context.JK.makeAbsolute("/school/#{this.state.school.id}/student")

    msg = "Hello Students & Parents -

I'm writing to make you aware of a very interesting new option for private music lessons. A company called JamKazam has built remarkable new technology that lets musicians play together live in sync with studio quality audio from different locations over the Internet. Here's an example: https://www.youtube.com/watch?v=I2reeNKtRjg. Now they have built an online music lesson service that uses this technology: https://www.youtube.com/watch?v=wdMN1fQyD9k.

\n\nThis means that students can now take lessons online and much more conveniently from home. Parents don't have to leave work early to drive students to and from lessons during rush hour. A 30-minute lesson is just a 30-minute lesson at home, not a 90-minute expedition across town. And students can record lessons to refer back to them later.

\n\nIf the convenience of online lessons is attractive to your family, then you can use this link to sign up for online lessons: #{path}. After you sign up, someone from JamKazam will reach out to answer your questions and help you get set up and ready to go. Your student can continue to take lessons from the same instructor through this service if desired. The student will need access to a Windows or Mac computer, and you'll need basic Internet service at home. The service uses the built-in microphone and headphone jack on the computer for audio. You can also purchase a pro audio upgrade package from JamKazam for $49.99 that includes an audio interface (a small box that connects to the computer via a USB cable), a microphone, a microphone cable, and a microphone stand. This is optional, but will deliver superior audio quality in lessons.

\n\nThe music program directors are primarily concerned with giving our students the highest quality music education possible, so we encourage you to make whatever decision you feel is best for the student. That said, for students who take lessons through the JamKazam service, a portion of the lesson fees are distributed back into our music program booster fund, which helps to fund the program's expenses, and is a nice additional benefit. If you have more questions, you can send an email to support@jamkazam.com."

    return msg

  renderSchool: () ->
    firstNameErrors = context.JK.reactSingleFieldErrors('first_name', @state.inviteErrors)
    lastNameErrors = context.JK.reactSingleFieldErrors('last_name', @state.inviteErrors)
    emailErrors = context.JK.reactSingleFieldErrors('email', @state.inviteErrors)

    firstNameClasses = classNames({first_name: true, error: firstNameErrors?, field: true})
    lastNameClasses = classNames({last_name: true, error: lastNameErrors?, field: true})
    emailClasses = classNames({email: true, error: emailErrors?, field: true})
    sendInvitationClasses = classNames({'button-orange': true, disabled: this.state.sending})

    if @state.teacher
      title = 'invite teacher'
      help = `<p>Send invitations to teachers who teach through your music school. Teachers who accept your invitation
        will be associated with your music school. Any revenues we collect for lessons delivered by these teachers will
        be processed such that we remit your school's share of these revenues to you, and you will then be responsible
        to distribute the teacher's share of these revenues, per the JamKazam terms of service. You will also have the
        option to manage scheduling of lessons for students sourced to the teacher from the JamKazam marketplace. </p>`
    else
      title = 'invite student'
      help = `<p>
        Send invitations to students who you have acquired through your own marketing initiatives (versus students
        JamKazam has brought to you). We will not bill these students for lessons, or will we withhold portions of such
        billings. All billing and management of your own students remains yours to manage, per the JamKazam terms of
        service.
      </p>`

    `<div>
      <div className="content-head">
        <img className="content-icon" src="/assets/content/icon_add.png" height={19} width={19}/>

        <h1>{title}</h1>
      </div>
      <div className="dialog-inner">

        {help}

        <div className={firstNameClasses}>
          <label>First Name: </label>
          <input type="text" defaultValue={this.firstName} name="first_name"/>
          {firstNameErrors}
        </div>

        <div className={lastNameClasses}>
          <label>Last Name: </label>
          <input type="text" defaultValue={this.lastName} name="last_name"/>
          {lastNameErrors}
        </div>

        <div className={emailClasses}>
          <label>Email Name: </label>
          <input type="text" defaultValue={this.email} name="email"/>
          {emailErrors}
        </div>

        <div className="actions">
          <a onClick={this.doCancel} className="button-grey">CANCEL</a>
          <a onClick={this.doInvite} className={sendInvitationClasses}>SEND INVITATION</a>
        </div>
      </div>
    </div>`

  render: () ->
    school = this.state.school

    if !school?
      return `<div>no school</div>`

    if school.education && !@state.teacher
      @renderEducation()
    else
      @renderSchool()


})