'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

exports.parseDate = parseDate;
exports.isDate = isDate;
exports.isArrayLike = isArrayLike;
exports.encodeFilter = encodeFilter;
exports.decodeFilter = decodeFilter;

var _base64Url = require('base64-url');

var _base64Url2 = _interopRequireDefault(_base64Url);

var _isodate = require('@segment/isodate');

var _isodate2 = _interopRequireDefault(_isodate);

var _dehumanizeDate = require('dehumanize-date');

var _dehumanizeDate2 = _interopRequireDefault(_dehumanizeDate);

var _constants = require('../constants');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// const iso8601RegExp = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/

var shortDateRegExp = /^(\d{4})-(\d{2})-(\d{2})$/;

/**
 * Attempt to parse a datestring, returning `null` if it can't be parsed
 * @param {string} possibleDate [description]
 * @return {date|null} returns a Date object or `null` if not a date.
 */
function parseDate(value) {
  if (shortDateRegExp.test(value)) {
    var m = value.match(shortDateRegExp);
    value = new Date(m[1], m[2] - 1, m[3]).toISOString();
  }
  return _isodate2.default.parse(value) || (0, _dehumanizeDate2.default)(value);
}

function isDate(v) {
  if (v instanceof Date) return true;
  if (typeof v !== 'string') return false;
  return _isodate2.default.is(v) || (0, _dehumanizeDate2.default)(v) != null;
}

function isArrayLike(type) {
  switch (type) {
    case _constants.FIELD_TYPE_SPACE_DELIMITED:
    case _constants.FIELD_TYPE_ARRAY:
    case _constants.FIELD_TYPE_STRING_OR_ARRAY:
    case _constants.FIELD_TYPE_NUMBER_OR_ARRAY:
      return true;
    default:
      return false;
  }
}

/**
 * Encode an object into a URL safe base64 string
 * @param {object} filter Any object to encode
 * @return {string} URL safe base64 encoded string
 */
function encodeFilter(filter) {
  return _base64Url2.default.encode(Buffer.from((0, _stringify2.default)(filter)));
}

/**
 * Decode URL safe base64String to an object
 * @param {string} base64String base64 encoded string
 * @return {object} decoded object
 */
function decodeFilter(base64String) {
  return JSON.parse(_base64Url2.default.decode(base64String).toString());
}
//# sourceMappingURL=filter_helpers.js.map