/* globals i18n */

import Component from 'ember-component';

const TOTAL_LABEL = i18n('Total');
const DATE_LABEL = i18n('Date');

export default Component.extend({
  classNames: ['clearfix', 'align-right'],

  // Passed-in properties:
  isDisabled: true,
  revenueData: null,
  subscriptionsData: null,

  actions: {
    exportData() {
      if (!this.get('revenueData') || !this.get('subscriptionsData')) { return; }

      let rows = this._generateDataRows();
      let CSV = this._convertDataToCSV(rows);

      this._downloadCSV(CSV);
    }
  },

  // Helper functions for exporting data:
  _generateDataRows() {
    let revenues = this.get('revenueData.datasets');
    let subs = this.get('subscriptionsData.datasets');
    let labels = this.get('revenueData.labels');

    return labels.map((label, index) => {
      let row = { [DATE_LABEL]: label };
      let totalRevenue = 0;

      revenues.forEach(revenue => {
        row[revenue.label] = revenue.data[index];
        totalRevenue += revenue.data[index];
      });

      row[TOTAL_LABEL] = totalRevenue.toFixed(2);

      subs.forEach(sub => {
        row[sub.label] = sub.data[index];
      });

      return row;
    });
  },

  _convertDataToCSV(dataRows) {
    let CSV = `${ Object.keys(dataRows[0]).join() }\r\n`;

    dataRows.forEach(row => {
      CSV += `${ Object.keys(row).map(key => `"${ row[key] }"`).join() }\r\n`;
    });

    return CSV;
  },

  _downloadCSV(CSV) {
    let fileName = 'TwitchDashboardReport_.csv';

    if (typeof window.navigator.msSaveBlob === 'function') {
      // IE 10+
      let blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });

      return window.navigator.msSaveBlob(blob, fileName);
    }

    let anchor = document.createElement('a');
    let encodedURI = encodeURIComponent(CSV);

    if (typeof anchor.download === 'undefined') {
      // Safari
      anchor.href = `data:attachment/csv;charset=utf-8,${ encodedURI }`;
    } else {
      // Firefox, Chrome (HTML5)
      anchor.href = `data:text/csv;charset=utf-8,${ encodedURI }`;
      anchor.download = fileName;
    }

    anchor.target = '_blank';
    anchor.style = 'visibility: hidden'; // hidden visibility to not affect DOM layout

    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
  }
});
