context = window

SessionsActions = @SessionsActions

@FindSessionOpen = React.createClass({

  mixins: [Reflux.listenTo(@AppStore, "onAppInit")
           Reflux.listenTo(@SessionsStore, "onSessionsChanged")]

  searched_ever: false
  registeredInfiniteScroll: false

  getInitialState: () ->
    {active: false, sessions: [], searching: false, count: 0, currentPage: 0, end: false}

  sessionResults: () ->
    results = []
    for session in @state.sessions
        results.push(`<FindSessionRow mode={this.props.mode} session={session} />`)
    results

  help: () ->
    if this.props.mode == 'open'
      `<div className="find-session-help">
          <h3>How This Page Works</h3>
          <p>This page will show only public jam sessions.</p>
          <p>Most recent sessions are shown an the top.</p>
          <p>This list of public sessions does not auto-update.  You will have to push the REFRESH button to see new sessions.</p>
      </div>`
    else if this.props.mode == 'my'
      `<div className="find-session-help">
          <h3>How This Page Works</h3>
          <p>This page will show sessions tailored for you:</p>
          <ul>
              <li>sessions created by a friend (<a href='#' onClick={this.inviteFriends.bind(this)}>invite others to JamKazam</a>)</li>
              <li>sessions for which you have an invitation</li>
              <li>sessions for which you have a RSVP</li>
          </ul>
          <br/>
          <h3>Sit Back and Relax</h3>
          <p>This page will automatically update when a friend creates a session, or you are invited to one.</p>
          <p>So if your friend is creating a session soon, just sit tight and watch for sessions to show up!</p>
      </div>`
    else
      `<div className="find-session-help">
          <h3>How This Page Works</h3>
          <p>This page will show these scheduled sessions:</p>
          <ul>
              <li>public jam sessions</li>
              <li>sessions created by a friend (<a href='#' onClick={this.inviteFriends.bind(this)}>invite others to JamKazam</a>)</li>
              <li>sessions for which you have an invitation</li>
              <li>sessions for which you have a RSVP</li>
          </ul>
          <br/>
          <h3>Reserve a spot</h3>
          <p>If you find a session you are interested in attending later, then click the RSVP icon to reserve your spot.</p><p>An email will be sent to the creator of the session, and they can then approve your request.</p>
          <h3>Schedule your Own</h3>
          <p>Don't see a session you like?  You can schedule your own session for others to RSVP to at the <a href="/client#/createSession">create session</a> screen. You will receive emails when others RSVP.</p>
      </div>`


  refresh: () ->
    if @state.searching
      return

    SessionsActions.clearSessions.trigger(@props.mode, @query())

  render: () ->
    results = @sessionResults()

    className = "content-body-scroller sessions-for-open"

    if(@props.active)
      className = className + " active"

    firstTime = null
    if results.length == 0
      if @state.searching
        results = `<tr key="single"><td colSpan="3" className="none-found">... Searching ...</td></tr>`
      else
        # help = @help()
        results = `<tr key="single"><td colSpan="3" className="none-found">None Found</td></tr>`

    if @state.end && results.length > 5
      results.push(`<tr><td colSpan="3" className="end-of-results">End of Search Results<div className="spacer"></div></td></tr>`)
    help = @help()

    refreshButtonClasses = "button-grey btn-refresh"

    if @state.searching
      refreshButtonClasses = refreshButtonClasses += " disabled"


    `<div className={className}>
        <div className="content-wrapper">
            <div id="sessions-active" className="session-container">
                <div className="header-zone">
                  <h2>sessions for me</h2>


                    <div className="refresh-btn">
                        <a  href="/client#/findSession" style={{textDecoration:'none'}} disabled={this.state.searching}
                            className={refreshButtonClasses} onClick={this.refresh.bind(this)}>REFRESH<span className="extra"></span></a>
                    </div>
                  <div className="search-box">
                      <input className="session-keyword-srch" type="text" name="search"
                             placeholder="Search by Keyword"/>
                  </div>
                </div>

                <br/>

                <div className="findsession-container">
                    <table id="sessions-active" className="findsession-table" cellspacing="0"
                           cellpadding="0" border="0">
                        <thead>
                        <tr>
                            <th align="left" width="40%">SESSION</th>
                            <th align="left" width="45%">MUSICIANS</th>
                            <th align="left" width="10%" style={{textAlign:'center'}}>ACTIONS</th>
                        </tr>
                        </thead>
                        <tbody>
                          {results}
                        </tbody>
                    </table>
                </div>
                {help}
            </div>
        </div>
    </div>`


  query: () ->

    $root = $(this.getDOMNode())
    keyword = $root.find('input.session-keyword-srch').val()
    if keyword == ''
      keyword = undefined
    query =
      keyword: keyword

    query

  componentDidMount: () ->
    @EVENTS = context.JK.EVENTS
    @rest = context.JK.Rest()
    @logger = context.JK.logger


  componentDidUpdate: (prevProps, prevState) ->

    if !@props.screenActive && prevProps.screenActive
      @searched_ever = false

    if @props.screenActive && @props.active && !@searched_ever
      SessionsActions.updateSessions.trigger(@props.mode)
      @searched_ever = true

    #if @props.active && !prevProps.active && !@searched_ever

    $root = $(this.getDOMNode())
    $scroller = $root

    if !@registeredInfiniteScroll
      @registerInfiniteScroll($scroller)

  registerInfiniteScroll: ($scroller) ->
    @registeredInfiniteScroll = true

    $scroller.off('scroll')
    $scroller.on('scroll', () =>

      # be sure to not fire off many refreshes when user hits the bottom
      return if @state.searching

      return if @state.end

      if $scroller.scrollTop() + $scroller.innerHeight() + 400 >= $scroller[0].scrollHeight
       SessionsActions.updateSessions.trigger(@props.mode, @query())
    )

  inviteFriends:() ->
    JK.InvitationDialogInstance.showEmailDialog();

  onAppInit: (@app) ->
    return

  onSessionsChanged: (sessionsChanged) ->
    if sessionsChanged.type == @props.mode
      @setState(sessionsChanged)

})