/* jshint node:true */
'use strict';

// Escape the textDelimiters contained in the field
/*(https://tools.ietf.org/html/rfc4180)
   7.  If double-quotes are used to enclose fields, then a double-quote
   appearing inside a field must be escaped by preceding it with
   another double quote.
   For example: "aaa","b""bb","ccc"
*/

module.exports = function escapedDelimiters(textDelimiter, rowDelimiter) {
  let endOfLine = '\n';

  if (typeof textDelimiter !== 'string') {
    throw new TypeError('Invalid param "textDelimiter", must be a string.');
  }

  if (typeof rowDelimiter !== 'string') {
    throw new TypeError('Invalid param "rowDelimiter", must be a string.');
  }

  let textDelimiterRegex = new RegExp("\\" + textDelimiter, 'g');
  let escapedDelimiter = textDelimiter + textDelimiter;

  return function(value) {
    if (!value.replace) return value;
    // Escape the textDelimiters contained in the field
    var newValue = value.replace(textDelimiterRegex, escapedDelimiter);
    // Escape the whole field if it contains a rowDelimiter or a linebreak
    if (newValue.indexOf(rowDelimiter) >= 0 || newValue.indexOf(endOfLine) >= 0) {
      newValue = textDelimiter + newValue + textDelimiter;
    }

    return newValue;
  };
};

@@ -796,16 +796,295 @@
 miter;%0A%0A
+  const enclosingCondition = (textDelimiter === '%22') ? %0A    (value) =%3E (value.indexOf(rowDelimiter) %3E= 0 %7C%7C %0A        value.indexOf(endOfLine) %3E= 0 %7C%7C%0A        value.indexOf('%22') %3E= 0)%0A    : (value) =%3E (value.indexOf(rowDelimiter) %3E= 0 %7C%7C %0A        value.indexOf(endOfLine) %3E= 0);%0A%0A
   return
@@ -1098,24 +1098,24 @@
 on(value) %7B%0A
-
     if (!val
@@ -1346,88 +1346,58 @@
 reak
-%0A    if (newValue.indexOf(rowDelimiter) %3E= 0 %7C%7C newValue.indexOf(endOfLine) %3E= 0
+ or double quote%0A    if (enclosingCondition(value)
 ) %7B%0A

fix for https://tools.ietf.org/html/rfc4180#page-3 paragraph 7