/*global window, rJS, RSVP, console, Plotly */
/*jslint nomen: true, indent: 2 */
(function (window, rJS, RSVP, Plotly, wendelin) {
  "use strict";

  var gadget_klass = rJS(window);

  function getPlotData(raw_lo, raw_hi, raw_qci, raw_date) {
    var color,
      color_array = [
        {'color': '#1f77b4'},
        {'color': '#ff7f0e'},
        {'color': '#2ca02c'},
        {'color': '#d62728'},
        {'color': '#9467bd'},
        {'color': '#8c564b'},
        {'color': '#e377c2'},
        {'color': '#7f7f7f'},
        {'color': '#bcbd22'},
        {'color': '#17becf'}
      ],
      qci_list = [...new Set(...raw_qci)],
      qci_count = qci_list.length,
      data_count = raw_date.length,
      data_list = [],
      qci,
      date,
      lo,
      hi,
      qci_idx,
      i,
      j;
    qci_list.sort(function(a, b) {
      return a - b;
    });
    for (i = 0; i < qci_count; i += 1) {
      qci = qci_list[i];
      date = [];
      lo = [];
      hi = [];
      for (j = 0; j < data_count; j += 1) {
        qci_idx = raw_qci[j].indexOf(qci);
        if (qci_idx == -1) {
          continue;
        }

        date.push(raw_date[j]);
        lo.push(raw_lo[j][qci_idx]);
        hi.push(raw_hi[j][qci_idx]);
      }

      color = color_array[i % color_array.length];
      data_list.push({
        x: date,
        marker: {
          size: 4
        },
        mode: 'lines+markers',
        y: lo,
        type: 'scatter',
        line: color,
        name: 'QCI ' + qci,
        legendgroup: 'legendgroup' + qci,
        hovertemplate: 'Date: %{x}<br>Link Speed: %{y} Mbit/s'
      });
      data_list.push({
        x: date,
        mode: 'lines',
        y: hi,
        type: 'scatter',
        line: color,
        opacity: 0.3,
        showlegend: false,
        fill: 'tonexty',
        legendgroup: 'legendgroup' + qci,
        hoverinfo: 'none'
      });
    }
    return data_list;
  }

  gadget_klass
    .declareAcquiredMethod("getSetting", "getSetting")
    .declareAcquiredMethod("jio_get", "jio_get")
    .declareAcquiredMethod("jio_getAttachment", "jio_getAttachment")
    .declareService(function () {
      var gadget = this;
      return loopEventListener(window, 'resize', false, function () {
        Plotly.Plots.resize(gadget.element.querySelector('.graph-upload-link'));
        Plotly.Plots.resize(gadget.element.querySelector('.graph-download-link'));
      });
    })
    .declareMethod('render', function (option_dict) {
      var gadget = this,
        i,
        download_data,
        upload_data,
        label_list = ["evt", "qci", "dl_lo", "dl_hi", "ul_lo", "ul_hi"];
      return new RSVP.Queue().push(function () {
          return wendelin.getArrayRawSlice(gadget, option_dict.data_array_key);
        })
        .push(function (result) {
          var graph_data = nj.unpack(result.pick( null, label_list)),
            date = [],
            qci = [],
            dl_lo = [],
            dl_hi = [],
            ul_lo = [],
            ul_hi = [],
            raw_qci,
            raw_dl_lo,
            raw_dl_hi,
            raw_ul_lo,
            raw_ul_hi,
            download_link = gadget.element.querySelector('.graph-download-link'),
            upload_link = gadget.element.querySelector('.graph-upload-link');
          for (i = 0; i < graph_data.length; i += 1) {
            if (date.indexOf(graph_data[i][0]) == -1) {
              date.push(graph_data[i][0]);
              qci.push(raw_qci);
              dl_lo.push(raw_dl_lo);
              dl_hi.push(raw_dl_hi);
              ul_lo.push(raw_ul_lo);
              ul_hi.push(raw_ul_hi);
              raw_qci = [graph_data[i][1]];
              raw_dl_lo = [graph_data[i][2] / 1e6];
              raw_dl_hi = [graph_data[i][3] / 1e6];
              raw_ul_lo = [graph_data[i][4] / 1e6];
              raw_ul_hi = [graph_data[i][5] / 1e6];
            } else {
              raw_qci.push(graph_data[i][1]);
              raw_dl_lo.push(graph_data[i][2] / 1e6);
              raw_dl_hi.push(graph_data[i][3] / 1e6);
              raw_ul_lo.push(graph_data[i][4] / 1e6);
              raw_ul_hi.push(graph_data[i][5] / 1e6);
            }
          }
          qci.push(raw_qci);
          dl_lo.push(raw_dl_lo);
          dl_hi.push(raw_dl_hi);
          ul_lo.push(raw_ul_lo);
          ul_hi.push(raw_ul_hi);
          qci.shift();
          dl_lo.shift();
          dl_hi.shift();
          ul_lo.shift();
          ul_hi.shift();
          date.forEach(function (element, index) {
            date[index] = new Date(element * 1000);
          });
          download_data = getPlotData(dl_lo, dl_hi, qci, date);
          upload_data = getPlotData(ul_lo, ul_hi, qci, date);
          Plotly.newPlot(
            download_link,
            download_data,
            {
              'title' : 'Download Link',
              'xaxis': {
                'autorange': true,
                'autosize': true
              },
              'yaxis': {
                title: {
                  text: 'Mbit/s'
                }
              }
            }
          );
          Plotly.newPlot(
             upload_link,
             upload_data,
             {
              'title' : 'Upload Link',
              'xaxis': {
                'autorange': true,
                'autosize': true
              },
              'yaxis': {
                title: {
                  text: 'Mbit/s'
                }
              }
            }
          );
          gadget.element.querySelector('.ui-icon-spinner').hidden = true;
        });
    });

}(window, rJS, RSVP, Plotly, wendelin));
