context = window

SessionsActions = @SessionsActions

@FindSessionFriends = React.createClass({

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

  TYPE_SESSION: 'my'
  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 session={session} />`)
    results

  help: () ->
    `<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>`

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

    SessionsActions.clearSessions.trigger(@TYPE_SESSION, @query())

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

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

    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>`

    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.active && !prevProps.active && !@searched_ever
      SessionsActions.updateSessions.trigger('my')
      @searched_ever = true

    $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

      if @state.end
        return

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

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

  onAppInit: (@app) ->
    return

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

})