$ ->
  
  dgchart = 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-dangerous-goods-page').length > 0)

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

    class DgChartBuilder
      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: ->
        thePoints = JSON.parse @$domData.val()
        thePoints.slice(0, 30)

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

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

      getData: ->
        config = {
          type: 'bar',
          data: {
            labels: @parseXaxis(),
            datasets: [{
              label: Yii.t('app', 'Dangerous Goods Number'),
              data: @parseYaxis(),
              backgroundColor: 'rgba(151,187,205,0.2)',
              borderColor: 'rgba(151,187,205,1)',
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            title: {
              display: true,
              text: Yii.t('app', 'Dangerous Goods Statistic')
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Code')
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Quantity')
                }
              }]
            }
          }
        };
        
        return config

      drawGraph: ->
        
        dgchart.destroy() if(dgchart)  
        dgchart = new Chart(@context, @getData())

    class DgStatsForm

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

        $("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", @$form).click ->
          $input = $('input', @)
          if $input.is(':checked')
            $input.attr('checked', false)
          else
            $input.attr('checked', true)


      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/dangerousGoodsFilter"
          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 DgChartBuilder($("#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 DgStatsForm($("#stats-form"))
