'use strict';

// Generated by CoffeeScript 2.1.1
// lib.cs.misc - Check the status of code repositories under a root directory.
// Copyright (C) 2016 Dario Giovannetti <dev@dariogiovannetti.net>

// This file is part of lib.cs.misc.

// lib.cs.misc is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// lib.cs.misc is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with lib.cs.misc.  If not, see <http://www.gnu.org/licenses/>.
var $, Papa;

$ = require('jquery');

require('bootstrap');

require('bootstrap-table');

Papa = require('papaparse');

// TODO: Change this to a proper BootstrapTable extension
module.exports.exportBootstrapTableToCSV = function (table, button) {
  var blob, column, csv, drow, field, fields, i, index, j, k, len, len1, len2, link, options, ref, ref1, row, rows;
  options = table.bootstrapTable('getOptions');
  fields = [];
  ref = options.columns[0];
  for (i = 0, len = ref.length; i < len; i++) {
    column = ref[i];
    field = {};
    // TODO: Document that the title of the first field should not be just
    //       "ID", otherwise Excel will think it is a SYLK file and raise
    //       warnings
    // https://annalear.ca/2010/06/10/why-excel-thinks-your-csv-is-a-sylk/
    if (column.CSVexportAs == null) {
      field.title = column.title;
    } else if (column.CSVexportAs !== false) {
      field.title = column.CSVexportAs;
    } else {
      continue;
    }
    field.fieldName = column.field;
    if (column.CSVexporter != null) {
      field.exporter = column.CSVexporter;
    } else {
      field.exporter = function (value, row, index) {
        return value;
      };
    }
    fields.push(field);
  }
  rows = [];
  ref1 = table.bootstrapTable('getData');
  for (index = j = 0, len1 = ref1.length; j < len1; index = ++j) {
    drow = ref1[index];
    row = [];
    for (k = 0, len2 = fields.length; k < len2; k++) {
      field = fields[k];
      row.push(field.exporter(drow[field.fieldName], drow, index));
    }
    rows.push(row);
  }
  csv = Papa.unparse({
    fields: function () {
      var l, len3, results;
      results = [];
      for (l = 0, len3 = fields.length; l < len3; l++) {
        field = fields[l];
        results.push(field.title);
      }
      return results;
    }(),
    data: rows
  });
  blob = new Blob([csv], {
    type: 'text/csv'
  });
  link = $("<a>").attr({
    "download": options.CSVexportFileName,
    "href": window.URL.createObjectURL(blob)
  }).insertAfter(button);
  // .trigger("click"); doesn't work
  link[0].click();
  return link.remove();
};