import _ from 'lodash';

const isRootLocaleComment =
  reply => (reply.depth === 1 && reply.body.length === 4 && reply.body.substring(0, 2) === '# ');

export const toObject = (body) => {
  const object = {};
  const lines = body.split(/\n/);
  lines.forEach((line) => {
    const message = line.split(':');
    if (message.length === 2) {
      object[message[0].trim()] = message[1].trim();
    }
  });
  return object;
};

export const getMessages = (replies) => {
  const localesMap = {};
  const messages = {};
  const sortedReplies = _.sortBy(replies, 'net_rshares');

  Object.keys(sortedReplies).forEach((key) => {
    const reply = sortedReplies[key];
    if (isRootLocaleComment(reply)) {
      localesMap[reply.permlink] = reply.body.replace('#', '').replace(' ', '').toLowerCase();
      messages[localesMap[reply.permlink]] = {};
    }
  });

  Object.keys(sortedReplies).forEach((key) => {
    const reply = sortedReplies[key];
    const locale = localesMap[reply.parent_permlink];
    if (locale) {
      const object = toObject(reply.body);
      messages[locale] = Object.assign(messages[locale], object);
    }
  });

  return messages;
};

export const getLocale = (appLocale, messages) => {
  const browserLocale = navigator.language || navigator.userLanguage; // eslint-disable-line
  let locale = appLocale || browserLocale;
  locale = locale.substr(0, 2);
  locale = messages[locale] ? locale : 'en';
  return locale;
};

@@ -278,23 +278,33 @@
 nst 
-message
+separatorPosition
  = line.
 spli
@@ -299,21 +299,23 @@
  = line.
-split
+indexOf
 (':');%0A 
@@ -321,32 +321,185 @@
     
-if (message.length === 2
+const key = separatorPosition %3E 0 ? line.slice(0, separatorPosition) : '';%0A    const value = separatorPosition %3E 0 ? line.slice(separatorPosition + 1) : '';%0A    if (key && value
 ) %7B%0A
@@ -515,18 +515,11 @@
 ect%5B
-message%5B0%5D
+key
 .tri
@@ -529,18 +529,13 @@
 %5D = 
-message%5B1%5D
+value
 .tri

Allow translation that include ':' character