import SimpleSchema from 'simpl-schema';
import { getSetting } from '../modules/settings';
import { debug } from 'meteor/vulcan:lib';

export const Strings = {};

export const Domains = {};

export const addStrings = (language, strings) => {
  if (typeof Strings[language] === 'undefined') {
    Strings[language] = {};
  }
  Strings[language] = {
    ...Strings[language],
    ...strings
  };
};

export const getString = ({id, values, defaultMessage, locale}) => {
  const messages = Strings[locale] || {};
  let message = messages[id];

  // use default locale
  if(!message) {
    debug(`\x1b[32m>> INTL: No string found for id "${id}" in locale "${locale}".\x1b[0m`);
    message = Strings[defaultLocale] && Strings[defaultLocale][id];

    // if default locale hasn't got the message too
    if(!message && locale !== defaultLocale)
      debug(`\x1b[32m>> INTL: No string found for id "${id}" in the default locale ("${defaultLocale}").\x1b[0m`);
  }

  if (message && values) {
    Object.keys(values).forEach(key => {
      // note: see replaceAll definition in vulcan:lib/utils
      message = message.replaceAll(`{${key}}`, values[key]);
    });
  }
  return message;
};

export const registerDomain = (locale, domain) => {
  Domains[domain] = locale;
};

export const defaultLocale = getSetting('locale', 'en');

export const Locales = [];

export const registerLocale = locale => {
  Locales.push(locale);
};

/*

Look for type name in a few different places
Note: look into simplifying this

*/
export const isIntlField = fieldSchema => {
  return fieldSchema.intl;
};

/*

Generate custom IntlString SimpleSchema type

*/
export const getIntlString = () => {
  const schema = {
    locale: {
      type: String,
      optional: true
    },
    value: {
      type: String,
      optional: true
    }
  };

  const IntlString = new SimpleSchema(schema);
  IntlString.name = 'IntlString';
  return IntlString;
};

/*

Check if a schema has at least one intl field

*/
export const schemaHasIntlFields = schema => Object.keys(schema).some(fieldName => isIntlField(schema[fieldName]));

/*

Custom validation function to check for required locales

See https://github.com/aldeed/simple-schema-js#custom-field-validation

*/
export const validateIntlField = function() {
  let errors = [];

  // go through locales to check which one are required
  const requiredLocales = Locales.filter(locale => locale.required);

  requiredLocales.forEach((locale, index) => {
    const strings = this.value;
    const hasString = strings && Array.isArray(strings) && strings.some(s => s && s.locale === locale.id && s.value);
    if (!hasString) {
      const originalFieldName = this.key.replace('_intl', '');
      errors.push({
        id: 'errors.required',
        path: `${this.key}.${index}`,
        properties: { name: originalFieldName, locale: locale.id }
      });
    }
  });

  if (errors.length > 0) {
    // hack to work around the fact that custom validation function can only return a single string
    return `intlError|${JSON.stringify(errors)}`;
  }
};

@@ -128,16 +128,74 @@
 :lib';%0A%0A
+export const defaultLocale = getSetting('locale', 'en');%0A%0A
 export c
@@ -439,16 +439,17 @@
 .strings
+,
 %0A  %7D;%0A%7D;
@@ -477,16 +477,17 @@
 ing = (%7B
+ 
 id, valu
@@ -512,16 +512,17 @@
 , locale
+ 
 %7D) =%3E %7B%0A
@@ -523,20 +523,18 @@
  =%3E %7B%0A  
-cons
+le
 t messag
@@ -534,20 +534,30 @@
  message
-s
  = 
+'';%0A%0A  if (
 Strings%5B
@@ -568,83 +568,134 @@
 le%5D 
-%7C%7C %7B%7D;%0A  let message = messages
+&& Strings%5Blocale%5D%5Bid%5D) %7B%0A    message = Strings%5Blocale%5D
 %5Bid%5D;%0A
-%0A
   
-// use 
+%7D else if (Strings%5B
 default
- l
+L
 ocale
-%0A  if(!message
+%5D && Strings%5BdefaultLocale%5D%5Bid%5D
 ) %7B%0A
@@ -774,16 +774,56 @@
 locale%7D%22
+, using defaultLocale %22$%7BdefaultLocale%7D%22
 .%5Cx1b%5B0m
@@ -898,108 +898,39 @@
 d%5D;%0A
-%0A    // if default locale hasn't got the message too%0A    if(!message && locale !== defaultLocale)%0A  
+  %7D else if (defaultMessage) %7B%0A
     
@@ -987,19 +987,41 @@
 id%7D%22 in 
-the
+locale %22$%7Blocale%7D%22, using
  default
@@ -1025,16 +1025,16 @@
 ult 
-local
+messag
 e 
-(
 %22$%7Bd
@@ -1043,17 +1043,17 @@
 ault
-Local
+Messag
 e%7D%22
-)
 .%5Cx1
@@ -1066,28 +1066,47 @@
 ;%0A  
-%7D%0A%0A  if (message && 
+  message = defaultMessage;%0A  %7D%0A%0A  if (
 valu
@@ -1396,66 +1396,8 @@
 %7D;%0A%0A
-export const defaultLocale = getSetting('locale', 'en');%0A%0A
 expo

Refactor getString