$ ->
  
  statchart = null
  opts =
    lines: 13
    length: 7
    width: 4
    radius: 10
    corners: 1 
    rotate: 0
    color: '#000'
    speed: 1
    trail: 60
    shadow: false
    hwaccel: false
    className: 'spinner'
    zIndex: 2e9
    top: 5
    left: 'auto'
  
  if ($('#stats-page').length > 0)

    $(".icon-calendar").click ->
      $(@).siblings('.date-picker').datepicker('show')

    class ChartBuilder
      constructor: (@$dom, @$domData) ->
        @context = @$dom.get(0).getContext("2d")
        @points = @getPoints()
        @fitSize()
        @drawGraph()

      fitSize: ->
        $container = $(@$dom.parent())
        @$dom.attr('width', $container.width())
        @$dom.attr('height', $container.height())

      getPoints: ->
        JSON.parse @$domData.val()

      parseXaxis: ->
        point.x for point in @points

      parseYaxis: ->
        parseInt(point.y, 10) for point in @points

      getData: ->
        data =
          labels: @parseXaxis()
          datasets: [
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            data: @parseYaxis()
          ]
        return data

      drawGraph: ->
      	
        if(statchart)
          statchart.destroy()   
      	
        statchart = new Chart(@context).Line(@getData())

    class StatsForm

      constructor: (@$form) ->
        @attachStartPicker()
        @attachEndPicker()
        @attachCheckboxes()
        @attachSpeedSlider()

        
        $("button[type='submit']", @$form).click =>
          @getStats()
          false

        $("button[type='export']", @$form).on 'click', (ev) =>
          theTarget = $(ev.currentTarget).data('target')
          @exportStats(theTarget)
          false

        $("button[type='export']", @$form).prop("disabled", true)
 
      getUnixStart: ($dom) ->
        moment($dom.datepicker('getDate')).startOf('day').unix()

      getUnixEnd: ($dom) ->
      	moment($dom.datepicker('getDate')).endOf('day').unix()+3600

      attachStartPicker: ->
        $picker = $("#datepicker-start-date", @$form)
        $picker.change =>
          $("#start-timestamp", @$form).val(@getUnixStart($picker))

      attachEndPicker: ->
        $picker = $("#datepicker-end-date", @$form)
        $picker.change =>
          $("#end-timestamp", @$form).val(@getUnixEnd($picker))

      attachCheckboxes: ->
        $("#gates button, #vehicles button", @$form).click ->
          $input = $('input', @)
          if $input.is(':checked')
            $input.attr('checked', false)
          else
            $input.attr('checked', true)

      attachSpeedSlider: ->
        $("#slider-range", @$form).slider
          range: true
          min: 10
          max: 300
          step: 5
          slide: (event, ui) ->
            $("#min-speed", @$form).val ui.values[0]
            $("#max-speed", @$form).val ui.values[1]

      clearGraph: ->
        canvas = $("#graph-canvas").get(0)
        canvas.width = canvas.width
        
      getStats: ->
        spinner = new Spinner(opts).spin($("#spinner").get(0))
        @clearGraph()
        $("button[type='export']", @$form).prop("disabled", true)
                    
        $.ajax
          type : "GET"
          url : "#{settings.baseUrl}/stats/filter"
          data : @$form.serialize()
          timeout: 60000
          
          success: (html) ->
            spinner.stop()
            $("button[type='export']").prop("disabled", false)
            $("#table-container").html(html)
            $("#table-container table").dataTable
            
              bSort: false
            new ChartBuilder($("#graph-canvas"), $("#graph-data"))
            
            
          error: (message) ->
            spinner.stop()  


      exportStats: (theTarget)->
        
        preparingFileModal = $("#preparing-file-modal")
        preparingFileModal.dialog modal: true
                
        $.fileDownload theTarget,
          
          preparingMessageHtml: Yii.t('app', 'We are preparing your report, please wait...')
          failMessageHtml: Yii.t('app', 'There was a problem generating your report, please try again.')
          httpMethod: "GET",
          data: @$form.serialize()
          
          successCallback: (url) ->
            preparingFileModal.dialog "close"

          failCallback: (responseHtml, url) ->
            preparingFileModal.dialog "close"
            $("#error-modal").dialog modal: true
        
    new StatsForm($("#stats-form"))
