type = ['primary', 'info', 'success', 'warning', 'danger'];

/* POTENTIAL SECURITY FLAW, LOOK INTO */
function htmlDecode(input){
  var doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent
}

var data = htmlDecode(dashboardData.data)
var displaySamepleData = false;
var json = null;
if(data == "[]"){
  displaySamepleData = true;
}
else{
  json = JSON.parse(data)
  console.log(json);
  var allGames = {};
  var hits = []
  var misses = []
  var dateLabels = []
  var curSum = 0;
  var curHits = 0;
  var curMisses = 0;

  /* Parses all needed data sent from the controller into a nice big "AllGames" dictionary.
  Creates an entry for each session, and an entry for each game in each session, then puts all game
  details inside */
  json.forEach(session => {
    var games = session.games
    games.forEach(game => {
      curSum = parseInt(game.hits) + parseInt(game.misses);
      curHits = Math.round(parseInt(game.hits) / curSum * 10000) / 100;
      curMisses = Math.round(parseInt(game.misses) / curSum * 10000) / 100;
      if(!allGames[session.info.session_id]){
        allGames[session.info.session_id] = {};
        allGames[session.info.session_id]["notes"] = session.info.notes;
        allGames[session.info.session_id]["hits"] = [curHits];
        allGames[session.info.session_id]["misses"] = [curMisses];
        allGames[session.info.session_id]["dates"] = [game.session_data_id];
        allGames[session.info.session_id]["games"] = {};
      }
      else{
        allGames[session.info.session_id]["hits"].push(curHits);
        allGames[session.info.session_id]["misses"].push(curMisses);
        allGames[session.info.session_id]["dates"].push(game.session_data_id);
      }
      if(game.time_sequence !== null){
        allGames[session.info.session_id]["games"][game.session_data_id] = {};
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"] = {};
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["game_id"] = game.game_id;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["description"] = game.description;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["sequence"] = game.sequence;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["mode"] = game.mode;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["time"] = game.time;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["delay_time"] = game.delay_time;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["num_of_pads"] = game.num_of_pads;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["type"] = game.type;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["station_id"] = game.station_id;
        allGames[session.info.session_id]["games"][game.session_data_id]["specs"]["setup"] = game.pad_arrangement;

        allGames[session.info.session_id]["games"][game.session_data_id]["pad"] = [];
        allGames[session.info.session_id]["games"][game.session_data_id]["time"] = [];
        allGames[session.info.session_id]["games"][game.session_data_id]["miss"] = [];

        let sequence = game.time_sequence.split(",")
        for(tuple of sequence){
          let split = tuple.split(":");
          allGames[session.info.session_id]["games"][game.session_data_id]["pad"].push(split[0]);
          if(split[1] == "-1"){
            allGames[session.info.session_id]["games"][game.session_data_id]["time"].push(null);
            allGames[session.info.session_id]["games"][game.session_data_id]["miss"].push(0);
          }
          else{
            allGames[session.info.session_id]["games"][game.session_data_id]["time"].push(split[1]);
            allGames[session.info.session_id]["games"][game.session_data_id]["miss"].push(null);
          }
        }
      }
      else{
        allGames[session.info.session_id]["games"][game.session_data_id] = {};
        allGames[session.info.session_id]["games"][game.session_data_id]["sequence"] = "No game data";
      }
      //These are used to populate the top chart (which isn't of much use anymore and should probably be removed)
      hits.push(curHits);
      misses.push(curMisses);
      dateLabels.push(game.session_data_id)
    });
  });
  console.log(allGames);
}

demo = {
  initPickColor: function() {
    $('.pick-class-label').click(function() {
      var new_class = $(this).attr('new-class');
      var old_class = $('#display-buttons').attr('data-class');
      var display_div = $('#display-buttons');
      if (display_div.length) {
        var display_buttons = display_div.find('.btn');
        display_buttons.removeClass(old_class);
        display_buttons.addClass(new_class);
        display_div.attr('data-class', new_class);
      }
    });
  },

  initDocChart: function() {
    chartColor = "#FFFFFF";

    // General configuration for the charts with Line gradientStroke
    gradientChartOptionsConfiguration = {
      maintainAspectRatio: false,
      legend: {
        display: false
      },
      tooltips: {
        bodySpacing: 4,
        mode: "nearest",
        intersect: 0,
        position: "nearest",
        xPadding: 10,
        yPadding: 10,
        caretPadding: 10
      },
      responsive: true,
      scales: {
        yAxes: [{
          display: 0,
          gridLines: 0,
          ticks: {
            display: false
          },
          gridLines: {
            zeroLineColor: "transparent",
            drawTicks: false,
            display: false,
            drawBorder: false
          }
        }],
        xAxes: [{
          display: 0,
          gridLines: 0,
          ticks: {
            display: false
          },
          gridLines: {
            zeroLineColor: "transparent",
            drawTicks: false,
            display: false,
            drawBorder: false
          }
        }]
      },
      layout: {
        padding: {
          left: 0,
          right: 0,
          top: 15,
          bottom: 15
        }
      }
    };

    ctx = document.getElementById('lineChartExample').getContext("2d");

    gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
    gradientStroke.addColorStop(0, '#80b6f4');
    gradientStroke.addColorStop(1, chartColor);

    gradientFill = ctx.createLinearGradient(0, 170, 0, 50);
    gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)");
    gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)");

    myChart = new Chart(ctx, {
      type: 'line',
      responsive: true,
      data: {
        labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
        datasets: [{
          label: "Active Users",
          borderColor: "#f96332",
          pointBorderColor: "#FFF",
          pointBackgroundColor: "#f96332",
          pointBorderWidth: 2,
          pointHoverRadius: 4,
          pointHoverBorderWidth: 1,
          pointRadius: 4,
          fill: true,
          backgroundColor: gradientFill,
          borderWidth: 2,
          data: [542, 480, 430, 550, 530, 453, 380, 434, 568, 610, 700, 630]
        }]
      },
      options: gradientChartOptionsConfiguration
    });
  },

  initDashboardPageCharts: function() {
    
    ///coding train tutorial structure, chart.js/////////////
    window.addEventListener('load', setup);

      async function setup() {
        const myctx = document.getElementById('myChart').getContext('2d');//time series
        const myChart = new Chart(myctx, {
          type: 'line',
          data: {
            labels: 
              dateLabels,
            datasets: [
              {
                label: 'Hits',
                data: hits,
                fill: false,
                borderColor: 'rgba(99, 132, 255, 1)',
                backgroundColor: 'rgba(99, 132, 255, 0.5)',
                borderWidth: 1,
              },
              {
                label: 'Misses',
                data: misses,
                fill: false,
                borderColor: 'rgba(255, 99, 132, 1)',
                backgroundColor: 'rgba(255, 99, 132, 0.5)',
                borderWidth: 1,
              },
            ]
          },
          options: {
            scales: {
              yAxes: [{
                barPercentage: 1.6,
                gridLines: {
                  drawBorder: false,
                  color: 'rgba(29,140,248,0.0)',
                  zeroLineColor: "transparent",
                },
                ticks: {
                  suggestedMin: 0,
                  suggestedMax: 100,
                  padding: 20,
                  fontColor: "#9e9e9e",
                  callback: function (value) {
                    return (value + '%');
                  }
                }
              }],
      
              xAxes: [{
                barPercentage: 1.6,
                gridLines: {
                  drawBorder: false,
                  color: 'rgba(0,242,195,0.1)',
                  zeroLineColor: "transparent",
                },
                ticks: {
                  padding: 1,
                  fontColor: "#9e9e9e",
                  callback: function(value) { 
                    //return new Date(value).toLocaleDateString('en-US', {weekday:'long', day:'numeric', month:'short', year:'numeric'}); 
                    return value;
                },
                }
              }]
            }
          },
        });

        $('.main-select').change(function(){
          var newSession = $(this).children("option:selected").val().toString();
          var data = myChart.config.data;
          if(newSession == "All"){
            data.datasets[0].data = hits;
            data.datasets[1].data = misses;
            data.labels = dateLabels;
        
            $('.session-notes').text("No session selected");
          }
          else{
            data.datasets[0].data = allGames[newSession]["hits"];
            data.datasets[1].data = allGames[newSession]["misses"];
            data.labels = allGames[newSession]["dates"];
        
            $('.session-notes').text(allGames[newSession]["notes"]);
          }
          myChart.update();
        });

        const sequencectx = document.getElementById('sequenceChart').getContext('2d');//time series
        const sequenceChart = new Chart(sequencectx, {
          type: 'bar',
          data: {
            labels: 
              dateLabels,
            datasets: [
              {
                label: 'Time',
                data: [],
                fill: false,
                borderColor: 'rgba(99, 132, 255, 1)',
                backgroundColor: 'rgba(99, 132, 255, 0.5)',
                borderWidth: 1,
              }/**,{
                label: 'Misses',
                data: hits,
                pointStyle: 'crossRot',
                pointRadius: 5,
                fill: false,
                borderColor: 'rgba(255, 99, 132, 1)',
                backgroundColor: 'rgba(255, 99, 132, 0.5)',
                borderWidth: 1,
              }*/
            ]
          },
          options: {
            scales: {
              yAxes: [{
                barPercentage: 1,
                gridLines: {
                  drawBorder: false,
                  color: 'rgba(29,140,248,0.0)',
                  zeroLineColor: "transparent",
                },
                ticks: {
                  suggestedMin: 0,
                  suggestedMax: 100,
                  padding: 20,
                  fontColor: "#9e9e9e",
                  callback: function (value) {
                    return (value + "ms");
                  }
                }
              }],
      
              xAxes: [{
                barPercentage: 1,
                gridLines: {
                  drawBorder: false,
                  color: 'rgba(0,242,195,0.1)',
                  zeroLineColor: "transparent",
                },
                ticks: {
                  padding: 1,
                  fontColor: "#9e9e9e",
                  callback: function(value) { 
                    //return new Date(value).toLocaleDateString('en-US', {weekday:'long', day:'numeric', month:'short', year:'numeric'}); 
                    return value;
                  },
                },
                scaleLabel: {
                  display: true,
                  labelString: 'Pad Number',
                  fontColor: "#CBCBCB",
                  fontSize: 14,
                }
              }]
            },
            //onClick: processBarClick()
          },
        });

        initPadDiagram(sequencectx, sequenceChart);

      }
  },

  initGoogleMaps: function() {
    var myLatlng = new google.maps.LatLng(40.748817, -73.985428);
    var mapOptions = {
      zoom: 13,
      center: myLatlng,
      scrollwheel: false, //we disable de scroll over the map, it is a really annoing when you scroll through page
      styles: [{
          "elementType": "geometry",
          "stylers": [{
            "color": "#1d2c4d"
          }]
        },
        {
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#8ec3b9"
          }]
        },
        {
          "elementType": "labels.text.stroke",
          "stylers": [{
            "color": "#1a3646"
          }]
        },
        {
          "featureType": "administrative.country",
          "elementType": "geometry.stroke",
          "stylers": [{
            "color": "#4b6878"
          }]
        },
        {
          "featureType": "administrative.land_parcel",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#64779e"
          }]
        },
        {
          "featureType": "administrative.province",
          "elementType": "geometry.stroke",
          "stylers": [{
            "color": "#4b6878"
          }]
        },
        {
          "featureType": "landscape.man_made",
          "elementType": "geometry.stroke",
          "stylers": [{
            "color": "#334e87"
          }]
        },
        {
          "featureType": "landscape.natural",
          "elementType": "geometry",
          "stylers": [{
            "color": "#023e58"
          }]
        },
        {
          "featureType": "poi",
          "elementType": "geometry",
          "stylers": [{
            "color": "#283d6a"
          }]
        },
        {
          "featureType": "poi",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#6f9ba5"
          }]
        },
        {
          "featureType": "poi",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "color": "#1d2c4d"
          }]
        },
        {
          "featureType": "poi.park",
          "elementType": "geometry.fill",
          "stylers": [{
            "color": "#023e58"
          }]
        },
        {
          "featureType": "poi.park",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#3C7680"
          }]
        },
        {
          "featureType": "road",
          "elementType": "geometry",
          "stylers": [{
            "color": "#304a7d"
          }]
        },
        {
          "featureType": "road",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#98a5be"
          }]
        },
        {
          "featureType": "road",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "color": "#1d2c4d"
          }]
        },
        {
          "featureType": "road.highway",
          "elementType": "geometry",
          "stylers": [{
            "color": "#2c6675"
          }]
        },
        {
          "featureType": "road.highway",
          "elementType": "geometry.fill",
          "stylers": [{
            "color": "#9d2a80"
          }]
        },
        {
          "featureType": "road.highway",
          "elementType": "geometry.stroke",
          "stylers": [{
            "color": "#9d2a80"
          }]
        },
        {
          "featureType": "road.highway",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#b0d5ce"
          }]
        },
        {
          "featureType": "road.highway",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "color": "#023e58"
          }]
        },
        {
          "featureType": "transit",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#98a5be"
          }]
        },
        {
          "featureType": "transit",
          "elementType": "labels.text.stroke",
          "stylers": [{
            "color": "#1d2c4d"
          }]
        },
        {
          "featureType": "transit.line",
          "elementType": "geometry.fill",
          "stylers": [{
            "color": "#283d6a"
          }]
        },
        {
          "featureType": "transit.station",
          "elementType": "geometry",
          "stylers": [{
            "color": "#3a4762"
          }]
        },
        {
          "featureType": "water",
          "elementType": "geometry",
          "stylers": [{
            "color": "#0e1626"
          }]
        },
        {
          "featureType": "water",
          "elementType": "labels.text.fill",
          "stylers": [{
            "color": "#4e6d70"
          }]
        }
      ]
    };

    var map = new google.maps.Map(document.getElementById("map"), mapOptions);

    var marker = new google.maps.Marker({
      position: myLatlng,
      title: "Hello World!"
    });

    // To add the marker to the map, call setMap();
    marker.setMap(map);
  },

  showNotification: function(from, align) {
    color = Math.floor((Math.random() * 4) + 1);

    $.notify({
      icon: "tim-icons icon-bell-55",
      message: "Welcome to <b>Black Dashboard</b> - a beautiful freebie for every web developer."

    }, {
      type: type[color],
      timer: 8000,
      placement: {
        from: from,
        align: align
      }
    });
  }

};