#= require ./behavior

class window.StreetPatrol extends window.Behavior
  
  init: ->
    @events = []
    @ignoreEvents = true
    @reviewingEvents = false
    @eventsTimeout = 0
    @eventsTimer = null
    @serializeTimer = null
    @serializeTimeout = 60000
    @socket = io 'http://192.168.2.61:3000'
    @socket.on 'street-patrol-event', (data) => @onSocketMessage(data)
    $('#street-patrol-start-btn').click (event) => @onStreetPatrolStartBtnClick(event)
    $('#street-patrol-stop-btn').click (event) => @onStreetPatrolStopBtnClick(event)
    $('#street-patrol-review-session-btn').click (event) => @onStreetPatrolReviewSessionBtnClick(event)
    $('#street-patrol-delete-session-btn').click (event) => @onStreetPatrolDeleteSessionBtnClick(event)
    $('#street-patrol-events-container').delegate 'input', 'click', (event) => @onMangedOnSiteClick(event)
    $('#street-patrol-events-timeout').on 'change', (event) => @onStreetPatrolEventsTimeoutChange(event)
    $('#street-patrol-stop-btn').prop('disabled', true)
    $('#street-patrol-delete-session-btn').prop('disabled', true)
    $('#street-patrol-events-timeout').prop('disabled', true)
    $('#street-patrol-delete-session-btn').prop('disabled', true)
    cachedEvents = JSON.parse(localStorage.getItem("street-patrol-events"))
    if cachedEvents
      @events = cachedEvents
    @serializeTimer = setInterval @serializeTimerCallback, @serializeTimeout
  
  onStreetPatrolStartBtnClick: (event) =>
    $('#street-patrol-start-btn').prop('disabled', true);
    $('#street-patrol-stop-btn').prop('disabled', false);
    $('#street-patrol-events-timeout').prop('disabled', false);
    $('#street-patrol-review-session-btn').prop('disabled', true);
    $('#street-patrol-delete-session-btn').prop('disabled', true);
    @ignoreEvents = false
    @reviewingEvents = false
    @renderEventsList(@getFreshEvents())
    @handleTimer(parseInt($('#street-patrol-events-timeout').val()))
    
  onStreetPatrolStopBtnClick: (event) =>
    $('#street-patrol-start-btn').prop('disabled', false);
    $('#street-patrol-stop-btn').prop('disabled', true);
    $('#street-patrol-events-timeout').prop('disabled', true);
    $('#street-patrol-review-session-btn').prop('disabled', false);
    $('#street-patrol-delete-session-btn').prop('disabled', true);
    @handleTimer(0)
    @ignoreEvents = true
    
  onStreetPatrolReviewSessionBtnClick: (event) =>
    $('#street-patrol-delete-session-btn').prop('disabled', false);
    @reviewingEvents = true
    @renderEventsList(@events)
    
  onStreetPatrolDeleteSessionBtnClick: (event) =>
    @events = []
    @serializeEvents()
    @renderEventsList(@events)
    
  onMangedOnSiteClick: (event) =>
    eventId = $(event.target).parents().parents('tr').attr('id')
    isChecked = $(event.target).prop( "checked" )
    ev = _.find @events, (ev) -> ev.id == eventId
    ev.handledOnSite = isChecked
    @serializeEvents()
    return
  
  onStreetPatrolEventsTimeoutChange: (event) =>
    eventsTimeout = parseInt($(event.target).val())
    @handleTimer eventsTimeout
    
  onSocketMessage: (data) =>
    if @ignoreEvents
      return
    @addNewEvent(data)
    @renderEventsList(@getFreshEvents())
    return
    
  addNewEvent: (event) ->
    eventId = "street-patrol-event-" + (new Date()).getTime()
    @events.unshift _.extend event, {handledOnSite:false, id:eventId, expired:false}
    @serializeEvents()
    
  handleTimer: (timeout) =>
    @eventsTimeout = timeout
    if @eventsTimer
      clearInterval @eventsTimer
      @eventsTimer = null
    if timeout != 0
      newEventsTimer = setInterval @timerCallback, timeout
      @eventsTimer = newEventsTimer
  
  timerCallback: () =>
    @markExpiredEvents(@eventsTimeout)
    @renderEventsList(@getFreshEvents())
    @serializeEvents()
    
  serializeTimerCallback: () =>
    @serializeEvents()
  
  markExpiredEvents: (timeout) =>
    _.each @events, (event) =>
      if (moment().unix() - event.timestamp > timeout)
        event.expired = true
  
  getFreshEvents: () =>
    freshEvents = _.filter @events, (event) =>
      return event.expired == false
    return freshEvents
    
  serializeEvents: () =>
    console.log("serializing")
    localStorage.setItem("street-patrol-events", JSON.stringify(@events))
    
  renderEventsList: (events) ->
    html = ''
    for event in events
      html += @renderEvent(event)
    $('#street-patrol-events-table > tbody').html html
    self = @
    $(".plate-popover").popover({
      # WARN:
      # DO NOT REMOVE THE TITLE OPTION!
      # there is a bug in our version of bootstrap such
      # that if we do not specify the 'title' option,
      # the function we will specify in the 'content' option 
      # is called twice, and we do not want it!      
      title: ' '
      #
      trigger: 'click',
      placement: 'bottom',
      html: true,
      content: () -> self.renderPopover($(this))
    });
    if events.length == 0
      $('#street-patrol-no-events-message').prop('hidden', false);
    else
      $('#street-patrol-no-events-message').prop('hidden', true);
    
  renderEvent: (event) ->
    checkboxDisabled = ''
    if @reviewingEvents
      checkboxDisabled ='disabled'
    isChecked = ''
    if event.handledOnSite == true
      isChecked = 'checked'
    html = '<tr id="' + event.id + '">' +
           '<td><input type="checkbox" class="street-patrol-checkbox" ' + isChecked + ' ' + checkboxDisabled + ' ></input></td>' +
           '<td class="plate-text">' + event.plate + '</td>' +
           '<td><span class="plate-popover"><img class="plate-overview-image" src="data:image/jpg;base64,' + event.image + '"/></span></td>' +
           '<td>' + @renderEventCheck(event.revision) + '</td>' +
           '<td>' + @renderEventCheck(event.insurance) + '</td>' +
           #'<td>54321</td>' +
           '<td class="event-date-time">' + moment.unix(event.timestamp).format("YYYY-MM-DD HH:mm:ss") + '</td>' +
           '</tr>'
    return html
  
  renderEventCheck: (success) ->
    if success
      return '<i class="street-patrol-icon-alarm icon-exclamation alarm-icon"></i>'
    else
      return '<i class="street-patrol-icon-ok icon-ok ok-icon"></i>'

  renderPopover: (element) =>
    eventId = $(event.target).parents().parents('tr').attr('id')
    ev = _.find @events, (ev) -> ev.id == eventId
    return '<div class="popover-box"><img class="plate-extended-image" src="data:image/jpg;base64,' + ev.image + '"/></div>'
    