'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getSubrecordSearchName = exports.getFirstItem = exports.getPreviousPageSearchDescriptor = exports.getNextPageSearchDescriptor = exports.getListType = exports.searchDescriptorToLocation = exports.advancedSearchConditionToNXQL = exports.fieldConditionToNXQL = exports.rangeFieldConditionToNXQL = exports.structuredDateFieldConditionToNXQL = exports.booleanConditionToNXQL = exports.valueToNXQL = exports.operatorToNXQL = exports.pathToNXQL = exports.normalizeCondition = exports.normalizeFieldCondition = exports.normalizeRangeFieldCondition = exports.normalizeBooleanCondition = exports.normalizeFieldValue = exports.normalizeListFieldValue = exports.normalizeStringFieldValue = exports.normalizeTimestampRangeEndValue = exports.normalizeTimestampRangeStartValue = undefined;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _warning = require('warning');

var _warning2 = _interopRequireDefault(_warning);

var _configHelpers = require('./configHelpers');

var _recordDataHelpers = require('./recordDataHelpers');

var _dataTypes = require('../constants/dataTypes');

var _searchOperators = require('../constants/searchOperators');

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

function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }

const getDataType = (fieldDescriptor, path) => (0, _get2.default)(fieldDescriptor, ['document', ...path.split('/'), _configHelpers.configKey, 'dataType']);

const normalizeTimestampRangeStartValue = exports.normalizeTimestampRangeStartValue = value => {
  if (value) {
    const timestamp = value.trim();

    if (timestamp) {
      return timestamp.indexOf('T') < 0 ? `${timestamp}T00:00:00.000` : timestamp;
    }
  }

  return null;
};

const normalizeTimestampRangeEndValue = exports.normalizeTimestampRangeEndValue = value => {
  if (value) {
    const timestamp = value.trim();

    if (timestamp) {
      return timestamp.indexOf('T') < 0 ? `${timestamp}T23:59:59.999` : timestamp;
    }
  }

  return null;
};

const normalizeStringFieldValue = exports.normalizeStringFieldValue = value => {
  let trimmed;

  if (value) {
    trimmed = value.trim();
  }

  return trimmed || null;
};

const normalizeListFieldValue = exports.normalizeListFieldValue = list => {
  let filtered;

  if (list) {
    filtered = list.map(value => normalizeStringFieldValue(value)).filter(value => !!value);
  }

  if (!filtered || filtered.size === 0) {
    return null;
  }

  if (filtered.size === 1) {
    return filtered.first();
  }

  return filtered;
};

const normalizeFieldValue = exports.normalizeFieldValue = value => _immutable2.default.List.isList(value) ? normalizeListFieldValue(value) : normalizeStringFieldValue(value);

const normalizeBooleanCondition = exports.normalizeBooleanCondition = (fieldDescriptor, condition) => {
  let childConditions = condition.get('value');

  if (childConditions) {
    /* Gotta do this mutual recursion */
    /* eslint-disable no-use-before-define */
    childConditions = childConditions.map(childCondition => normalizeCondition(fieldDescriptor, childCondition)).filter(childCondition => !!childCondition);
    /* eslint-enable no-use-before-define */
  }

  if (childConditions && childConditions.size > 0) {
    if (childConditions.size > 1) {
      return condition.set('value', childConditions);
    }

    return childConditions.get(0);
  }

  return null;
};

const normalizeRangeFieldCondition = exports.normalizeRangeFieldCondition = (fieldDescriptor, condition) => {
  const value = condition.get('value');

  if (value) {
    const path = condition.get('path');
    const dataType = getDataType(fieldDescriptor, path);

    let startValue = value.get(0);
    let endValue = value.get(1);

    if (dataType === _dataTypes.DATA_TYPE_DATETIME) {
      startValue = normalizeTimestampRangeStartValue(startValue);
      endValue = normalizeTimestampRangeEndValue(endValue);
    } else {
      startValue = normalizeStringFieldValue(startValue);
      endValue = normalizeStringFieldValue(endValue);
    }

    if (!startValue && !endValue) {
      return null;
    }

    if (!startValue) {
      return _immutable2.default.Map({
        op: _searchOperators.OP_LTE,
        path: condition.get('path'),
        value: endValue
      });
    }

    if (!endValue) {
      return _immutable2.default.Map({
        op: _searchOperators.OP_GTE,
        path: condition.get('path'),
        value: startValue
      });
    }

    return condition.set('value', _immutable2.default.List([startValue, endValue]));
  }

  return null;
};

const normalizeFieldCondition = exports.normalizeFieldCondition = (fieldDescriptor, condition) => {
  const value = normalizeFieldValue(condition.get('value'));

  if (value) {
    return condition.set('value', value);
  }

  return null;
};

const normalizeCondition = exports.normalizeCondition = (fieldDescriptor, condition) => {
  if (condition) {
    const operator = condition.get('op');

    switch (operator) {
      case _searchOperators.OP_AND:
      case _searchOperators.OP_OR:
        return normalizeBooleanCondition(fieldDescriptor, condition);
      case _searchOperators.OP_RANGE:
        return normalizeRangeFieldCondition(fieldDescriptor, condition);
      default:
        return normalizeFieldCondition(fieldDescriptor, condition);
    }
  }

  return null;
};

const operatorToNXQLMap = {
  [_searchOperators.OP_AND]: 'AND',
  [_searchOperators.OP_OR]: 'OR',
  [_searchOperators.OP_EQ]: '=',
  [_searchOperators.OP_LT]: '<',
  [_searchOperators.OP_LTE]: '<=',
  [_searchOperators.OP_GT]: '>',
  [_searchOperators.OP_GTE]: '>=',
  [_searchOperators.OP_MATCH]: 'ILIKE',
  [_searchOperators.OP_RANGE]: 'BETWEEN'
};

const pathToNXQL = exports.pathToNXQL = (fieldDescriptor, path) => {
  var _path$split = path.split('/'),
      _path$split2 = _toArray(_path$split);

  const partName = _path$split2[0],
        pathInPartArray = _path$split2.slice(1);

  const nxqlPartName = partName.substr(0, 4) === `${_recordDataHelpers.NS_PREFIX}:` ? partName.substr(4) : partName;

  const partDescriptor = (0, _get2.default)(fieldDescriptor, ['document', partName]);
  const nxqlPathInPartArray = [];

  for (let i = 0; i < pathInPartArray.length; i += 1) {
    const fieldName = pathInPartArray[i];
    const fieldPath = pathInPartArray.slice(0, i + 1);
    const fieldConfig = (0, _get2.default)(partDescriptor, [...fieldPath, _configHelpers.configKey]);
    const repeating = (0, _get2.default)(fieldConfig, 'repeating');

    nxqlPathInPartArray.push(repeating ? '*' : fieldName);
  }

  const nxqlPath = nxqlPathInPartArray.join('/');

  return `${nxqlPartName}:${nxqlPath}`;
};

const operatorToNXQL = exports.operatorToNXQL = operator => operatorToNXQLMap[operator];

const valueToNXQL = exports.valueToNXQL = (value, dataType = _dataTypes.DATA_TYPE_STRING) => {
  let nxqlValue;

  if (dataType === _dataTypes.DATA_TYPE_DATETIME || dataType === _dataTypes.DATA_TYPE_DATE) {
    // Timestamp values in searches must be given in UTC.

    nxqlValue = new Date(Date.parse(value)).toISOString();

    return `TIMESTAMP "${nxqlValue}"`;
  }

  if (dataType === _dataTypes.DATA_TYPE_INT) {
    nxqlValue = parseInt(value, 10);
  } else if (dataType === _dataTypes.DATA_TYPE_FLOAT) {
    nxqlValue = parseFloat(value);
  } else if (dataType === _dataTypes.DATA_TYPE_BOOL) {
    nxqlValue = value ? 1 : 0;
  } else {
    nxqlValue = value;
  }

  return JSON.stringify(nxqlValue);
};

const booleanConditionToNXQL = exports.booleanConditionToNXQL = (fieldDescriptor, condition) => {
  const operator = condition.get('op');
  const nxqlOp = operatorToNXQL(operator);

  if (nxqlOp) {
    const childConditions = condition.get('value');

    const nxql = childConditions.map(childCondition =>
    /* Gotta do this mutual recursion */
    /* eslint-disable no-use-before-define */
    advancedSearchConditionToNXQL(fieldDescriptor, childCondition))
    /* eslint-enable no-use-before-define */
    .join(` ${nxqlOp} `);

    return `(${nxql})`;
  }

  return '';
};

const structuredDateFieldConditionToNXQL = exports.structuredDateFieldConditionToNXQL = (fieldDescriptor, condition) => {
  // Convert structured date searches to searches on the earliest and latest scalar dates.

  // The UI has historically added one day to the latest day when computing the latest scalar
  // date. I don't know why. This has to be taken into account.

  const path = condition.get('path');
  const operator = condition.get('op');
  const value = condition.get('value');

  const earliestScalarDatePath = `${path}/dateEarliestScalarValue`;
  const latestScalarDatePath = `${path}/dateLatestScalarValue`;

  let convertedCondition;

  if (operator === _searchOperators.OP_RANGE) {
    // The structured date range overlaps the value range.

    const rangeStart = value.get(0);
    const rangeEnd = value.get(1);

    convertedCondition = _immutable2.default.fromJS({
      op: _searchOperators.OP_AND,
      value: [{
        path: earliestScalarDatePath,
        op: _searchOperators.OP_LTE,
        value: rangeEnd
      }, {
        path: latestScalarDatePath,
        op: _searchOperators.OP_GT,
        value: rangeStart
      }]
    });
  } else if (operator === _searchOperators.OP_CONTAIN) {
    // The structured date range contains the value date.

    convertedCondition = _immutable2.default.fromJS({
      op: _searchOperators.OP_AND,
      value: [{
        path: earliestScalarDatePath,
        op: _searchOperators.OP_LTE,
        value
      }, {
        path: latestScalarDatePath,
        op: _searchOperators.OP_GT, // Not GTE, because latest scalar date has one day added.
        value
      }]
    });
  } else if (operator === _searchOperators.OP_EQ) {
    // The earliest and latest dates of the structured date are the same, and are equal to the
    // value date.

    convertedCondition = _immutable2.default.fromJS({
      op: _searchOperators.OP_AND,
      value: [{
        path: earliestScalarDatePath,
        op: _searchOperators.OP_EQ,
        value
      }, {
        path: latestScalarDatePath,
        op: _searchOperators.OP_EQ,
        // GRRR. The latest scalar date has one day added.
        value: (0, _moment2.default)(value).add(1, 'day').format('YYYY-MM-DD')
      }]
    });
  } else if (operator === _searchOperators.OP_LT) {
    // The earliest date in the structured date is before the value date, i.e. some part of the
    // structured date exists before the value.

    convertedCondition = _immutable2.default.fromJS({
      path: earliestScalarDatePath,
      op: _searchOperators.OP_LT,
      value
    });
  } else if (operator === _searchOperators.OP_LTE) {
    // The earliest date in the structured date is before or equal to the value date.

    convertedCondition = _immutable2.default.fromJS({
      path: earliestScalarDatePath,
      op: _searchOperators.OP_LTE,
      value
    });
  } else if (operator === _searchOperators.OP_GT) {
    // The latest date in the structured date is after the value date, i.e. some part of the
    // structured date exists after the value.

    convertedCondition = _immutable2.default.fromJS({
      path: latestScalarDatePath,
      op: _searchOperators.OP_GT,
      // GRRR. The latest scalar date has one day added.
      value: (0, _moment2.default)(value).add(1, 'day').format('YYYY-MM-DD')
    });
  } else if (operator === _searchOperators.OP_GTE) {
    // The latest date in the structured date is after or equal to the value date.

    convertedCondition = _immutable2.default.fromJS({
      path: latestScalarDatePath,
      op: _searchOperators.OP_GT, // Not GTE, because latest scalar date has one day added.
      value
    });
  }

  process.env.NODE_ENV !== 'production' ? (0, _warning2.default)(convertedCondition, `The operator ${operator} is not supported for structured date fields. Search condition will be ignored.`) : void 0;

  return convertedCondition
  // eslint-disable-next-line no-use-before-define
  ? advancedSearchConditionToNXQL(fieldDescriptor, convertedCondition) : null;
};

const rangeFieldConditionToNXQL = exports.rangeFieldConditionToNXQL = (fieldDescriptor, condition) => {
  const path = condition.get('path');
  const dataType = getDataType(fieldDescriptor, path);

  if (dataType === _dataTypes.DATA_TYPE_STRUCTURED_DATE) {
    return structuredDateFieldConditionToNXQL(fieldDescriptor, condition);
  }

  const operator = condition.get('op');
  const values = condition.get('value');

  const nxqlPath = pathToNXQL(fieldDescriptor, path);
  const nxqlOp = operatorToNXQL(operator);

  const startValue = values.get(0);
  const endValue = values.get(1);

  const nxqlValue = [startValue, endValue].map(value => valueToNXQL(value, dataType)).join(' AND ');

  return `${nxqlPath} ${nxqlOp} ${nxqlValue}`;
};

const fieldConditionToNXQL = exports.fieldConditionToNXQL = (fieldDescriptor, condition) => {
  const path = condition.get('path');
  const dataType = getDataType(fieldDescriptor, path);

  let operator = condition.get('op');
  let value = condition.get('value');

  if (_immutable2.default.List.isList(value)) {
    // Expand or'ed values.

    return value.map(valueInstance => fieldConditionToNXQL(fieldDescriptor, condition.set('value', valueInstance))).join(' OR ');
  }

  if (dataType === _dataTypes.DATA_TYPE_STRUCTURED_DATE) {
    return structuredDateFieldConditionToNXQL(fieldDescriptor, condition);
  }

  if (operator === _searchOperators.OP_CONTAIN) {
    operator = _searchOperators.OP_MATCH;
    value = `%${value}%`;
  }

  const nxqlPath = pathToNXQL(fieldDescriptor, path);
  const nxqlOp = operatorToNXQL(operator);
  const nxqlValue = valueToNXQL(value, dataType);

  return `${nxqlPath} ${nxqlOp} ${nxqlValue}`;
};

const advancedSearchConditionToNXQL = exports.advancedSearchConditionToNXQL = (fieldDescriptor, condition) => {
  if (condition) {
    const operator = condition.get('op');

    switch (operator) {
      case _searchOperators.OP_AND:
      case _searchOperators.OP_OR:
        return booleanConditionToNXQL(fieldDescriptor, condition);
      case _searchOperators.OP_RANGE:
        return rangeFieldConditionToNXQL(fieldDescriptor, condition);
      default:
        return fieldConditionToNXQL(fieldDescriptor, condition);
    }
  }

  return null;
};

/**
 * Converts a search descriptor to a React Router location.
 */
const searchDescriptorToLocation = exports.searchDescriptorToLocation = searchDescriptor => {
  const recordType = searchDescriptor.get('recordType');
  const vocabulary = searchDescriptor.get('vocabulary');
  const csid = searchDescriptor.get('csid');
  const subresource = searchDescriptor.get('subresource');
  const searchQuery = searchDescriptor.get('searchQuery');

  const pathParts = ['/list', recordType, vocabulary, csid, subresource];
  const pathname = pathParts.filter(part => !!part).join('/');

  const as = searchQuery.get('as');
  const p = searchQuery.get('p');

  const asParam = as ? JSON.stringify(as.toJS()) : undefined;

  const pParam = typeof p === 'number' ? (p + 1).toString() : undefined;

  const queryString = _qs2.default.stringify(searchQuery.set('as', asParam).set('p', pParam).toJS());

  return {
    pathname,
    search: `?${queryString}`
  };
};

const getListType = exports.getListType = (config, searchDescriptor) => {
  if (searchDescriptor) {
    const subresource = searchDescriptor.get('subresource');

    if (subresource) {
      return (0, _get2.default)(config, ['subresources', subresource, 'listType']);
    }
  }

  return 'common';
};

/**
 * Returns a search descriptor that describes the next page of the search described by a given
 * descriptor.
 */
const getNextPageSearchDescriptor = exports.getNextPageSearchDescriptor = searchDescriptor => {
  const p = searchDescriptor.getIn(['searchQuery', 'p']) || 0;

  return searchDescriptor.setIn(['searchQuery', 'p'], p + 1);
};

/**
 * Returns a search descriptor that describes the previous page of the search described by a given
 * descriptor. Null is returned if the given descriptor is on the first page.
 */
const getPreviousPageSearchDescriptor = exports.getPreviousPageSearchDescriptor = searchDescriptor => {
  const p = searchDescriptor.getIn(['searchQuery', 'p']) || 0;

  if (p <= 0) {
    return null;
  }

  return searchDescriptor.setIn(['searchQuery', 'p'], p - 1);
};

/**
 * Returns the first item in list result data.
 */
const getFirstItem = exports.getFirstItem = (config, listData, listType = 'common') => {
  if (!listData) {
    return null;
  }

  const listTypeConfig = (0, _get2.default)(config, ['listTypes', listType]);

  if (!listTypeConfig) {
    return null;
  }

  const listNodeName = listTypeConfig.listNodeName,
        itemNodeName = listTypeConfig.itemNodeName;


  const items = listData.getIn([listNodeName, itemNodeName]);

  const item = _immutable2.default.List.isList(items) ? items.first() : items;

  return item;
};

/**
 * Returns a name for a search for subrecords.
 */
const getSubrecordSearchName = exports.getSubrecordSearchName = (csid, subrecordName) => `subrecord/${csid}/${subrecordName}`;