$ ->
  
  if ($('#stats-operators-statistics-page').length > 0)

    class ChartsBuilder
      
      constructor: () ->
        @initGraphs()
        
      initGraphs: () ->
      
        if ($('.stats-operators-statistics-search-results').length == 0)
          return
      
        @initApprovedVsInvalidViolationsTrendGraph('approved-vs-invalid-violations-trend-graph')
        
        @initUsersApprovedVsInvalidViolationsGraph('users-approved-vs-invalid-violations-graph')
        
        @initValidationDecisionsGraph(
          'validation-decisions-trend-graph',
          JSON.parse($('#validation-decisions-by-timespan-graph-data').val()),
          Yii.t('app','Invalid Violations Reasons Statistics')
        );
        
        @initUsersValidationDecisionsGraph()
        
      initApprovedVsInvalidViolationsTrendGraph: (containerId) ->
      
        containerEl = document.getElementById(containerId);
        if (containerEl == null)
          return
      
        ctx = containerEl.getContext('2d');
    
        approvedViolationsCountByTimespanGraphData = JSON.parse($('#approved-violations-count-by-timespan-graph-data').val());
        invalidViolationsCountByTimespanGraphData = JSON.parse($('#invalid-violations-count-by-timespan-graph-data').val());
    
        graphLables = _.keys(approvedViolationsCountByTimespanGraphData);
    
        approvedViolationsCountByTimespanGraphValues = _.values(approvedViolationsCountByTimespanGraphData);
        invalidViolationsCountByTimespanGraphValues = _.values(invalidViolationsCountByTimespanGraphData);
        
        config = {
          type: 'bar',
          data: {
            labels: graphLables,
            datasets: [{
              label: Yii.t('app', 'Approved Violations'),
              data: approvedViolationsCountByTimespanGraphValues,
              backgroundColor: 'rgba(92,184,92,0.2)',
              borderColor: 'rgba(92,184,92,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Invalid Violations'),
              data: invalidViolationsCountByTimespanGraphValues,
              backgroundColor: 'rgba(172,41,37,0.2)',
              borderColor: 'rgba(172,41,37,1)',
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            title: {
              display: true,
              text: Yii.t('app', 'Validated Violations Daily Trend')
            },
            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);
        
      initUsersApprovedVsInvalidViolationsGraph: (containerId) ->
      
        containerEl = document.getElementById(containerId);
        if (containerEl == null)
          return
        
        ctx = containerEl.getContext('2d');
    
        approvedViolationsCountByTimespanGraphData = JSON.parse($('#users-approved-violations-count-by-timespan-graph-data').val());
        
        invalidViolationsCountByTimespanGraphData = JSON.parse($('#users-invalid-violations-count-by-timespan-graph-data').val());
    
        graphLables = _.keys(approvedViolationsCountByTimespanGraphData);
    
        approvedViolationsCountByTimespanGraphValues = _.values(approvedViolationsCountByTimespanGraphData);
        invalidViolationsCountByTimespanGraphValues = _.values(invalidViolationsCountByTimespanGraphData);
        
        config = {
          type: 'bar',
          data: {
            labels: graphLables,
            datasets: [{
              label: Yii.t('app', 'Approved Violations'),
              data: approvedViolationsCountByTimespanGraphValues,
              backgroundColor: 'rgba(92,184,92,0.2)',
              borderColor: 'rgba(92,184,92,1)',
              borderWidth: 1
            },
            {
              label: Yii.t('app', 'Invalid Violations'),
              data: invalidViolationsCountByTimespanGraphValues,
              backgroundColor: 'rgba(172,41,37,0.2)',
              borderColor: 'rgba(172,41,37,1)',
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            title: {
              display: true,
              text: Yii.t('app', 'Validation Statistics')
            },
            tooltips: {
              mode: 'index',
              intersect: false,
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                display: true,
                stacked: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'User')
                },
                ticks: {
                  autoSkip: false
                }
              }],
              yAxes: [{
                stacked: true,
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Violations')
                },
                ticks: {
                  beginAtZero: true,
                  callback: (value) ->
                    if (value % 1 == 0)
                      return value
                }
              }]
            }
          }
        };
        
        chart = new Chart(ctx, config);
      
      initValidationDecisionsGraph: (containerId, validationDecisionsTrendsGraphData, title) ->
      
        validationDecisionsTrendsGraphData = _.omit(validationDecisionsTrendsGraphData, Yii.t('app','Approved Violations'))
      
        containerEl = document.getElementById(containerId);
        if (containerEl == null)
          return
      
        ctx = containerEl.getContext('2d');
        
        graphLables = _.keys(validationDecisionsTrendsGraphData);
    
        validationDecisionsTrendsGraphValues = _.values(validationDecisionsTrendsGraphData);
        
        config = {
          type: 'bar',
          data: {
            labels: graphLables
            datasets: [{
              label: title,
              data: validationDecisionsTrendsGraphValues,
              backgroundColor: 'rgba(169,169,169,0.5)',
              borderColor: 'rgba(169,169,169,1)',
              borderWidth: 1
            }],
          }
          options : {
            responsive: true,
            title: {
                display: true,
                text: title
            },
            legend: {
              display: false
            }
            tooltips: {
              mode: 'index',
              intersect: false,
              callbacks: {
                label: (tooltipItem, data) ->
                  return data['datasets'][0]['data'][tooltipItem['index']].toString()
              }
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                stacked: true,
                display: true,
                scaleLabel: {
                  display: true
                },
                ticks: {
                  autoSkip: false
                }
              }],
              yAxes: [{
                stacked: true,
                display: true,
                scaleLabel: {
                  display: true,
                  labelString: Yii.t('app', 'Violations')
                },
                ticks: {
                  beginAtZero: true,
                  callback: (value) ->
                    if (value % 1 == 0)
                      return value
                },
              }]
            }
          }
        }
        
        chart = new Chart(ctx, config);
    
      initUsersValidationDecisionsGraph: () =>
      
        usersValidationDecisions = JSON.parse($('#users-validation-decisions-by-timespan-graph-data').val())
        
        _.each(usersValidationDecisions, (element, index, list) =>
        
          @initValidationDecisionsGraph(
            'user-validation-decisions-trend-graph-' + element.user.id,
            element.data,
            Yii.t('app','User') + ': ' + element.user.name 
          )
          
        )
        
    class OperatorStatisticsSearchForm

      constructor: (@$form) ->
        @attachSelectPicker()
        
      attachSelectPicker: ->
        $('#operators-statistics-gate-filter').selectpicker();

    $(".icon-calendar").click ->
      $(@).siblings('.date-picker').datepicker('show')
      
    if ($('.stats-operators-statistics-search-results').length != 0)
      
      $('.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-operators-statistics-search-results').printThis({
          canvas: true,
          importStyle: true
        });
    else
      $('.print-btn').addClass('disabled')
        
    new OperatorStatisticsSearchForm($("#operator-statistics-search-form"))
    
    new ChartsBuilder()
