"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getAllI18n = getAllI18n;
exports.getPropertiesAsJSON = getPropertiesAsJSON;
exports.jsonToString = jsonToString;

var _fs = require("fs");

var _path = require("path");

var _logger = require("../../../logger");

var _unicodeConversion = require("./unicodeConversion");

function isComment(line) {
  return line[0] === '#';
}

function getPropertiesAsJSON(filePath) {
  try {
    const data = (0, _fs.readFileSync)(filePath);
    const source = data.toString();
    const i18nObj = {};
    source.split(/\r?\n\r?/).forEach(fline => {
      const line = fline.trim();

      if (!line || isComment(line)) {
        return;
      }

      const ind = line.indexOf('=');
      const key = line.slice(0, ind).replace(/\\ /g, ' ');
      let value = line.slice(ind + 1);
      value = (0, _unicodeConversion.convertUnicode)(value);

      if (key && value) {
        i18nObj[key] = value;
      }
    }, {});
    return i18nObj;
  } catch (err) {
    return {};
  }
}

function getLang(file) {
  const underScoreIndex = file.indexOf('_');
  let language = 'en_US';

  if (underScoreIndex !== -1) {
    language = file.substring(underScoreIndex + 1);
    language = language.slice(0, language.indexOf('.'));
  }

  return language;
}

function getAllI18n({
  folderPath,
  disableDefault,
  jsResourceI18nKeys,
  exclude = /^[^_]+$/,
  include = /\.properties$/
}) {
  try {
    const files = (0, _fs.readdirSync)(folderPath, 'utf8');
    const allLangI18n = {};
    const context = (0, _path.join)(process.cwd(), folderPath);
    files.forEach(file => {
      const filePath = (0, _path.join)(context, file);

      if (exclude.test(filePath) || !include.test(filePath)) {
        return;
      }

      const i18n = getPropertiesAsJSON(filePath);
      allLangI18n[getLang(file)] = disableDefault ? i18n : Object.assign({}, jsResourceI18nKeys, i18n);
    });
    return allLangI18n;
  } catch (err) {
    (0, _logger.errorLogger)(err);
    return {};
  }
}

function jsonToString(json, keySeperator) {
  let str = '{';
  const keys = Object.keys(json);
  keys.forEach((key, i) => {
    const value = json[key];

    if (!value) {
      return;
    }

    str += `"${keySeperator ? key.replace(/(\.|\\(\s+))/g, keySeperator) : key}":"${value.replace(/.?"/g, match => {
      if (match[0] === '\\') {
        return match;
      } else if (match.length === 2) {
        return `${match[0]}\\${match[1]}`;
      }

      return `\\${match}`;
    }).replace(/(\r\n|\n|\r)/g, '')}"`;

    if (i !== keys.length - 1) {
      str += ',';
    }
  });
  str += '}';
  return str;
}