/**
 * @function
 * @param {jQuery} $table
 * @param {bool} withHeader
 * @return string
 */
KuferTools.tableToCsv = function ($table, withHeader) {
  withHeader = withHeader === undefined ? false : withHeader;

  var csvSeperator = "\t";
  var csvNewLine = "\n";
  var result = '';

  /**
   * @param {Element} $row
   * @return string
   */
  function rowToCsv(row) {
    return $(row).find('th, td').toArray().map(function (cell) {
      return cell.textContent;
    }).reduce(function (x, y) {
      if (x !== '') {
        x += csvSeperator;
      }

      y = y.replace(/\t\n\r/g, ' ');

      return x + y;
    }, '');
  }

  /**
   * @param {jQuery} $tablePart
   * @return string
   */
  function tablePartToCsv($tablePart) {
    return $tablePart.find('tr').toArray().map(function(row) {
      return rowToCsv(row);
    }).reduce(function (x , y) {
      if (x !== '') {
        x += csvNewLine;
      }

      return x + y;
    }, '');
  }

  if (withHeader) {
    var $header = $table.find('thead');
    result += tablePartToCsv($header) + csvNewLine;
  }

  var $body = $table.find('tbody');
  result += tablePartToCsv($body);

  return result;
}

/**
 * @function
 * @param {jQuery} $table
 * @param {boolean} withHeader
 */
KuferTools.copyTableToClipboard = function($table, withHeader) {
  var sessionVar = 'kufertools.toolId.' + KuferTools.ToolId + '.kursdetails.belegungen.exporttable.withHeader';
  if (withHeader === undefined) {
    if (typeof window.sessionStorage !== "undefined" && window.sessionStorage.getItem(sessionVar) !== null) {
      withHeader = window.sessionStorage.getItem(sessionVar) === 'true';
    } else {
      var fnGetChoice = function ($element) {
        return $element.find('#shouldCopyHeaderToo').prop('checked');
      };
      var buttons = {
        'Ja': function () {
          var choice = fnGetChoice($(this));
          $(this).dialog('close');
          if (choice && typeof window.sessionStorage !== "undefined") {
            window.sessionStorage.setItem(sessionVar, 'true');
          }

          KuferTools.copyTableToClipboard($table, true);
        },
        'Nein': function () {
          var choice = fnGetChoice($(this));
          $(this).dialog('close');
          if (choice && typeof window.sessionStorage !== "undefined") {
            window.sessionStorage.setItem(sessionVar, 'false');
          }

          KuferTools.copyTableToClipboard($table, false);
        }
      };

      KuferTools.showMessage({
        meldung: 'Soll die Tabelle mit Spaltentiteln kopiert werden?<br/><br/>' +
          '<div><label style="font-weight: normal" for="shouldCopyHeaderToo">Diese Einstellung merken</label><input id="shouldCopyHeaderToo" value="1" type="checkbox" style="float: right"/></div>',
        title: 'Mit Spaltentiteln kopieren?',
        buttons: buttons,
        width: 'auto'
      });

      return;
    }
  }

  var csvData = KuferTools.tableToCsv($table, withHeader);

  KuferTools.copyTextToClipboard(csvData)
    .then(function() {
      document.getElementById('tnExportTableButtonClipboard').classList = 'btn btn-success';
    })
    .catch(function() {
      document.getElementById('tnExportTableButtonClipboard').classList = 'btn btn-danger';
      console.error('Fehler beim Kopieren ins Clipboard');
    });
};
