"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

require("core-js/modules/es.reflect.construct.js");

require("core-js/modules/es.symbol.js");

require("core-js/modules/es.symbol.description.js");

require("core-js/modules/es.object.to-string.js");

require("core-js/modules/es.symbol.iterator.js");

require("core-js/modules/es.array.iterator.js");

require("core-js/modules/es.string.iterator.js");

require("core-js/modules/web.dom-collections.iterator.js");

exports.__esModule = true;
exports.TextPlugin = void 0;

require("core-js/modules/es.array.concat.js");

require("core-js/modules/es.regexp.exec.js");

require("core-js/modules/es.string.split.js");

require("core-js/modules/es.string.replace.js");

require("core-js/modules/es.string.repeat.js");

require("core-js/modules/es.array.slice.js");

require("core-js/modules/es.regexp.constructor.js");

require("core-js/modules/es.regexp.to-string.js");

require("core-js/modules/es.object.get-prototype-of.js");

var _Cell = require("../../Cell");

var _errorMessage = require("../../error-message");

var _FunctionPlugin2 = require("./FunctionPlugin");

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/**
 * Interpreter plugin containing text-specific functions
 */
var TextPlugin = /*#__PURE__*/function (_FunctionPlugin) {
  _inherits(TextPlugin, _FunctionPlugin);

  var _super = _createSuper(TextPlugin);

  function TextPlugin() {
    _classCallCheck(this, TextPlugin);

    return _super.apply(this, arguments);
  }

  _createClass(TextPlugin, [{
    key: "concatenate",
    value:
    /**
     * Corresponds to CONCATENATE(value1, [value2, ...])
     *
     * Concatenates provided arguments to one string.
     *
     * @param ast
     * @param state
     */
    function concatenate(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('CONCATENATE'), function () {
        var _ref;

        return (_ref = '').concat.apply(_ref, arguments);
      });
    }
    /**
     * Corresponds to SPLIT(string, index)
     *
     * Splits provided string using space separator and returns chunk at zero-based position specified by second argument
     *
     * @param ast
     * @param state
     */

  }, {
    key: "split",
    value: function split(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('SPLIT'), function (stringToSplit, indexToUse) {
        var splittedString = stringToSplit.split(' ');

        if (indexToUse >= splittedString.length || indexToUse < 0) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.IndexBounds);
        }

        return splittedString[indexToUse];
      });
    }
  }, {
    key: "len",
    value: function len(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('LEN'), function (arg) {
        return arg.length;
      });
    }
  }, {
    key: "lower",
    value: function lower(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('LOWER'), function (arg) {
        return arg.toLowerCase();
      });
    }
  }, {
    key: "trim",
    value: function trim(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('TRIM'), function (arg) {
        return arg.replace(/^ +| +$/g, '').replace(/ +/g, ' ');
      });
    }
  }, {
    key: "proper",
    value: function proper(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('PROPER'), function (arg) {
        return arg.replace(/[^\s]+/g, function (word) {
          return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
        });
      });
    }
  }, {
    key: "clean",
    value: function clean(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('CLEAN'), function (arg) {
        // eslint-disable-next-line no-control-regex
        return arg.replace(/[\u0000-\u001F]/g, '');
      });
    }
  }, {
    key: "exact",
    value: function exact(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('EXACT'), function (left, right) {
        return left === right;
      });
    }
  }, {
    key: "rept",
    value: function rept(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('REPT'), function (text, count) {
        if (count < 0) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.NegativeCount);
        }

        return text.repeat(count);
      });
    }
  }, {
    key: "right",
    value: function right(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('RIGHT'), function (text, length) {
        if (length < 0) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.NegativeLength);
        } else if (length === 0) {
          return '';
        }

        return text.slice(-length);
      });
    }
  }, {
    key: "left",
    value: function left(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('LEFT'), function (text, length) {
        if (length < 0) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.NegativeLength);
        }

        return text.slice(0, length);
      });
    }
  }, {
    key: "mid",
    value: function mid(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('MID'), function (text, startPosition, numberOfChars) {
        if (startPosition < 1) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.LessThanOne);
        }

        if (numberOfChars < 0) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.NegativeLength);
        }

        return text.substring(startPosition - 1, startPosition + numberOfChars - 1);
      });
    }
  }, {
    key: "replace",
    value: function replace(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('REPLACE'), function (text, startPosition, numberOfChars, newText) {
        if (startPosition < 1) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.LessThanOne);
        }

        if (numberOfChars < 0) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.NegativeLength);
        }

        return text.substring(0, startPosition - 1) + newText + text.substring(startPosition + numberOfChars - 1);
      });
    }
  }, {
    key: "search",
    value: function search(ast, state) {
      var _this = this;

      return this.runFunction(ast.args, state, this.metadata('SEARCH'), function (pattern, text, startIndex) {
        if (startIndex < 1 || startIndex > text.length) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.LengthBounds);
        }

        var normalizedText = text.substring(startIndex - 1).toLowerCase();
        var index;

        if (_this.arithmeticHelper.requiresRegex(pattern)) {
          index = _this.arithmeticHelper.searchString(pattern, normalizedText);
        } else {
          index = normalizedText.indexOf(pattern.toLowerCase());
        }

        index = index + startIndex;
        return index > 0 ? index : new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.PatternNotFound);
      });
    }
  }, {
    key: "substitute",
    value: function substitute(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('SUBSTITUTE'), function (text, oldText, newText, occurrence) {
        var oldTextRegexp = new RegExp(oldText, 'g');

        if (occurrence === undefined) {
          return text.replace(oldTextRegexp, newText);
        }

        if (occurrence < 1) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.LessThanOne);
        }

        var match;
        var i = 0;

        while ((match = oldTextRegexp.exec(text)) !== null) {
          if (occurrence === ++i) {
            return text.substring(0, match.index) + newText + text.substring(oldTextRegexp.lastIndex);
          }
        }

        return text;
      });
    }
  }, {
    key: "find",
    value: function find(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('FIND'), function (pattern, text, startIndex) {
        if (startIndex < 1 || startIndex > text.length) {
          return new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.IndexBounds);
        }

        var shiftedText = text.substring(startIndex - 1);
        var index = shiftedText.indexOf(pattern) + startIndex;
        return index > 0 ? index : new _Cell.CellError(_Cell.ErrorType.VALUE, _errorMessage.ErrorMessage.PatternNotFound);
      });
    }
  }, {
    key: "t",
    value: function t(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('T'), function (arg) {
        if (arg instanceof _Cell.CellError) {
          return arg;
        }

        return typeof arg === 'string' ? arg : '';
      });
    }
  }, {
    key: "upper",
    value: function upper(ast, state) {
      return this.runFunction(ast.args, state, this.metadata('UPPER'), function (arg) {
        return arg.toUpperCase();
      });
    }
  }]);

  return TextPlugin;
}(_FunctionPlugin2.FunctionPlugin);

exports.TextPlugin = TextPlugin;
TextPlugin.implementedFunctions = {
  'CONCATENATE': {
    method: 'concatenate',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }],
    repeatLastArgs: 1,
    expandRanges: true
  },
  'EXACT': {
    method: 'exact',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'SPLIT': {
    method: 'split',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER
    }]
  },
  'LEN': {
    method: 'len',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'LOWER': {
    method: 'lower',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'MID': {
    method: 'mid',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER
    }]
  },
  'TRIM': {
    method: 'trim',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'T': {
    method: 't',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.SCALAR
    }]
  },
  'PROPER': {
    method: 'proper',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'CLEAN': {
    method: 'clean',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'REPT': {
    method: 'rept',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER
    }]
  },
  'RIGHT': {
    method: 'right',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER,
      defaultValue: 1
    }]
  },
  'LEFT': {
    method: 'left',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER,
      defaultValue: 1
    }]
  },
  'REPLACE': {
    method: 'replace',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  },
  'SEARCH': {
    method: 'search',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER,
      defaultValue: 1
    }]
  },
  'SUBSTITUTE': {
    method: 'substitute',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER,
      optionalArg: true
    }]
  },
  'FIND': {
    method: 'find',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }, {
      argumentType: _FunctionPlugin2.ArgumentTypes.NUMBER,
      defaultValue: 1
    }]
  },
  'UPPER': {
    method: 'upper',
    parameters: [{
      argumentType: _FunctionPlugin2.ArgumentTypes.STRING
    }]
  }
};