$ ->
  
  if ($('#stats-events-management-page').length > 0)
  
    class ChartsBuilder
      
      constructor: () ->
        @initGraphs()
        
      initGraphs: () ->
      
        @initViolationManagementGraph('violations-management-graph')
        @initViolationManagementByGateGraph('violations-management-by-gate-graph')
        @initViolationManagementExportedGraph('violations-management-exported-graph')
        
      initViolationManagementGraph: (containerId) ->
      
        chart = null
  
        ctx = document.getElementById(containerId).getContext('2d');
        
        violationsCountByTimestampGraphData = JSON.parse($('#violations-count-by-timespan-graph-data').val());
        approvedViolationsCountByTimestampGraphData = JSON.parse($('#approved-violations-count-by-timespan-graph-data').val());
        invalidViolationsCountByTimestampGraphData = JSON.parse($('#invalid-violations-count-by-timespan-graph-data').val());
        pendingViolationsCountByTimestampGraphData = JSON.parse($('#pending-violations-count-by-timespan-graph-data').val());
        
        graphLables = _.keys(violationsCountByTimestampGraphData);
        
        violationsCountByTimestampGraphValues = _.values(violationsCountByTimestampGraphData);
        approvedViolationsCountByTimestampGraphValues = _.values(approvedViolationsCountByTimestampGraphData);
        invalidViolationsCountByTimestampGraphValues = _.values(invalidViolationsCountByTimestampGraphData);
        pendingViolationsCountByTimestampGraphValues = _.values(pendingViolationsCountByTimestampGraphData);
        
        config = {
          type: 'bar',
          data: {
            labels: graphLables,
            datasets: [{
              label: Yii.t('app', 'Violations'),
              data: violationsCountByTimestampGraphValues,
              stack: 'Stack 0',
              backgroundColor: 'rgba(51,122,183,0.2)',
              borderColor: 'rgba(51,122,183,1)',
              borderWidth: 1        
            },
            {
              label: Yii.t('app', 'Approved Violations'),
              data: approvedViolationsCountByTimestampGraphValues,
              stack: 'Stack 1',
              backgroundColor: 'rgba(92,184,92,0.2)',
              borderColor: 'rgba(92,184,92,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Invalid Violations'),
              data: invalidViolationsCountByTimestampGraphValues,
              stack: 'Stack 1',
              backgroundColor: 'rgba(172,41,37,0.2)',
              borderColor: 'rgba(172,41,37,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Pending Violations'),
              data: pendingViolationsCountByTimestampGraphValues,
              stack: 'Stack 1',
              backgroundColor: 'rgba(240,173,78,0.2)',
              borderColor: 'rgba(240,173,78,1)',
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            title: {
              display: true,
              text: Yii.t('app', 'Violations Management Statistics')
            },
            tooltips: {
              mode: 'index',
              intersect: false,
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                display: true,
                stacked: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Date')
                },
                ticks: {
                  autoSkip: false
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Violations')
                },
                ticks: {
                  beginAtZero: true,
                  callback: (value) ->
                    if (value % 1 == 0)
                      return value
                },
                stacked: true
              }]
            }
          }
        };
        
        chart = new Chart(ctx, config);
        
      initViolationManagementByGateGraph: (containerId) ->
      
        chart = null
  
        ctx = document.getElementById(containerId).getContext('2d');
        
        violationsCountByGateGraphData = JSON.parse($('#violations-count-by-gate-graph-data').val());
        approvedViolationsCountByGateGraphData = JSON.parse($('#approved-violations-count-by-gate-graph-data').val());
        invalidViolationsCountByGateGraphData = JSON.parse($('#invalid-violations-count-by-gate-graph-data').val());
        exportedViolationsCountByGateGraphData = JSON.parse($('#exported-violations-count-by-gate-graph-data').val());
        
        graphLables = _.keys(violationsCountByGateGraphData);
        
        violationsCountByGateGraphValues = _.values(violationsCountByGateGraphData);
        approvedViolationsCountByGateGraphValues = _.values(approvedViolationsCountByGateGraphData);
        invalidViolationsCountByGateGraphValues = _.values(invalidViolationsCountByGateGraphData);
        exportedViolationsCountByGateGraphValues = _.values(exportedViolationsCountByGateGraphData);
        
        config = {
          type: 'bar',
          data: {
            labels: graphLables,
            datasets: [{
              label: Yii.t('app', 'Violations'),
              data: violationsCountByGateGraphValues,
              stack: 'Stack 0',
              backgroundColor: 'rgba(51,122,183,0.2)',
              borderColor: 'rgba(51,122,183,1)',
              borderWidth: 1        
            },
            {
              label: Yii.t('app', 'Approved Violations'),
              data: approvedViolationsCountByGateGraphValues,
              stack: 'Stack 1',
              backgroundColor: 'rgba(92,184,92,0.2)',
              borderColor: 'rgba(92,184,92,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Invalid Violations'),
              data: invalidViolationsCountByGateGraphValues,
              stack: 'Stack 1',
              backgroundColor: 'rgba(172,41,37,0.2)',
              borderColor: 'rgba(172,41,37,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Exported Violations'),
              data: exportedViolationsCountByGateGraphValues,
              stack: 'Stack 2',
              backgroundColor: 'rgba(169,169,169,0.2)',
              borderColor: 'rgba(169,169,169,1)',
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            title: {
              display: true,
              text: Yii.t('app', 'Violations Management Statistics') + ': ' + Yii.t('app', 'Gates')
            },
            tooltips: {
              mode: 'index',
              intersect: false,
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                display: true,
                stacked: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Gate')
                },
                ticks: {
                  autoSkip: false
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Violations')
                },
                ticks: {
                  beginAtZero: true,
                  callback: (value) ->
                    if (value % 1 == 0)
                      return value
                },
                stacked: true
              }]
            }
          }
        };
        
        chart = new Chart(ctx, config);
        
      initViolationManagementExportedGraph: (containerId) ->
      
        chart = null
  
        ctx = document.getElementById(containerId).getContext('2d');
        
        approvedViolationsCountByTimestampGraphData = JSON.parse($('#approved-violations-count-by-timespan-graph-data').val());
        exportedViolationsCountByTimestampGraphData = JSON.parse($('#exported-violations-count-by-timespan-graph-data').val());
        
        graphLables = _.keys(approvedViolationsCountByTimestampGraphData);
        
        approvedViolationsCountByTimestampGraphValues = _.values(approvedViolationsCountByTimestampGraphData);
        exportedViolationsCountByTimestampGraphValues = _.values(exportedViolationsCountByTimestampGraphData);
        
        config = {
          type: 'bar',
          data: {
            labels: graphLables,
            datasets: [{
              label: Yii.t('app', 'Approved Violations'),
              data: approvedViolationsCountByTimestampGraphValues,
              stack: 'Stack 0',
              backgroundColor: 'rgba(92,184,92,0.2)',
              borderColor: 'rgba(92,184,92,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Exported Violations'),
              data: exportedViolationsCountByTimestampGraphValues,
              stack: 'Stack 1',
              backgroundColor: 'rgba(169,169,169,0.2)',
              borderColor: 'rgba(169,169,169,1)',
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            title: {
              display: true,
              text: Yii.t('app', 'Exported Violations Statistics')
            },
            tooltips: {
              mode: 'index',
              intersect: false,
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                display: true,
                stacked: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Date')
                },
                ticks: {
                  autoSkip: false
                }
              }],
              yAxes: [{
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Violations')
                },
                ticks: {
                  beginAtZero: true,
                  callback: (value) ->
                    if (value % 1 == 0)
                      return value
                },
                stacked: true
              }]
            }
          }
        };
        
        chart = new Chart(ctx, config);
    
    class EventsManagementSearchForm
      
      constructor: () ->
        @initForm()
        
      initForm: () ->
        $('#stats-events-management-gate-filter').selectpicker();
    
        $(".icon-calendar").click ->
          $(@).siblings('.date-picker').datepicker('show')
      
        $('#stats-events-management-hour-filter-start').timepicker
          minuteStep: 10,
          appendWidgetTo: 'body',
          showMeridian: false,
          defaultTime: false

        $('#stats-events-management-hour-filter-end').timepicker
          minuteStep: 10,
          template: 'modal',
          appendWidgetTo: 'body',
          showSeconds: false,
          showMeridian: false,
          defaultTime: false
    
    class EventsManagementPrintControl
    
      constructor: () ->
        @init()
        
      init: () ->
        @initPrintButton()
        
      initPrintButton:() ->
        
        $('.print-btn').tooltip({
          placement:'right',
          title: Yii.t('app',"For a better print result, reduce portrait layout margins or use a landscape page layout")
        })
      
        $('.print-btn').click ->
          $('.stats-violation-management-search-results').printThis({
            canvas: true,
            importStyle: true
          });
          
    class EventsManagementExportControl
    
      constructor: (@$form) ->
        @init()
      
      init:() ->
        @initExportButton()
        
      initExportButton:() ->
        $("#events-management-export").on 'click', (ev) =>
          theTarget = $(ev.currentTarget).data('target')
          @exportStats(theTarget)
          false
      
      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: "POST"
          
          data: $("#events-management-search-form").serialize()
          
          successCallback: (url) ->
            preparingFileModal.dialog "close"

          failCallback: (responseHtml, url) ->
            preparingFileModal.dialog "close"
            $("#error-modal").dialog modal: true
            
    
    new EventsManagementSearchForm()
    
    if ($('.stats-violation-management-search-results').length != 0)
    
      new ChartsBuilder()
      
      new EventsManagementPrintControl()
      
      new EventsManagementExportControl()
    
    else
    
      $('.print-btn').addClass('disabled')
      
      $("#events-management-export").prop("disabled", true)
      