"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.newMLError = newMLError;
exports.isMLData = isMLData;
exports.isMLString = isMLString;
exports.replaceMLStringsWithStrings = replaceMLStringsWithStrings;
exports.replaceMLStringsWithMLData = replaceMLStringsWithMLData;
exports.replaceMLDataWithMLStrings = replaceMLDataWithMLStrings;
exports.ML_DATA = exports.ML_STRING = void 0;

var _isObject = _interopRequireDefault(require("./is-object"));

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

const ML_STRING = 'MLString';
exports.ML_STRING = ML_STRING;
const ML_DATA = 'MLData';
exports.ML_DATA = ML_DATA;

function newMLError(field, type) {
  return new Error(`"${field}" should be typeof ${type}`);
}

function isMLData(data) {
  if (!(0, _isObject.default)(data)) {
    return false;
  }

  for (const field in data) {
    if (typeof data[field] !== 'string' || field.length > 2) {
      return false;
    }
  }

  return true;
}

function isMLString(mlString) {
  if (!(0, _isObject.default)(mlString)) {
    return false;
  }

  if (!mlString.data) {
    return false;
  }

  if (mlString.type !== ML_STRING) {
    return false;
  }

  if (!isMLData(mlString.data)) {
    return false;
  }

  return true;
}

function replaceMLStringsWithStrings(obj, mlFields, lang) {
  obj = { ...obj
  };

  for (const field of mlFields) {
    if (!isMLString(obj[field])) {
      throw newMLError(field, ML_STRING);
    }

    obj[field] = obj[field].data[lang];
  }

  return obj;
}

function replaceMLStringsWithMLData(obj, mlFields) {
  obj = { ...obj
  };

  for (const field of mlFields) {
    if (!isMLString(obj[field])) {
      throw newMLError(field, ML_STRING);
    }

    obj[field] = obj[field].data;
  }

  return obj;
}

function replaceMLDataWithMLStrings(obj, mlFields) {
  obj = { ...obj
  };

  for (const field of mlFields) {
    if (typeof obj[field] === 'undefined') {
      continue;
    }

    if (!isMLData(obj[field])) {
      throw newMLError(field, ML_DATA);
    }

    obj[field] = {
      data: obj[field],
      type: ML_STRING
    };
  }

  return obj;
}