'use strict';

const defaults = require('lodash.defaults');
const fs = require('fs');
const path = require('path');
const osHomedir = require('os-homedir');

let config = null;

exports.reset = () => {
  config = null;
};

exports.get = () => {
  if (!config) {
    config = load();
  }
  return config;
};

function load() {
  const DEFAULT = path.join(__dirname, '..', 'config.json');
  const CUSTOM = path.join(osHomedir(), '.tldrrc');

  let defaultConfig = JSON.parse(fs.readFileSync(DEFAULT));
  defaultConfig.cache = path.join(osHomedir(), '.tldr');
  /*eslint-disable no-process-env */
  defaultConfig.proxy = process.env.HTTP_PROXY || process.env.http_proxy;
  /*eslint-enable no-process-env */

  let customConfig = {};
  try {
    customConfig = JSON.parse(fs.readFileSync(CUSTOM));
  } catch (ex) {
    /*eslint-disable */
    /*eslint-enable */
  }

  let merged = defaults(customConfig, defaultConfig);
  // Validating the theme settings
  let errors = Object.keys(!merged.themes ? {} : merged.themes).map(
    (key) => {
      return validateThemeItem(merged.themes[key], key);
    }
  );
  errors.push(validatePlatform(merged.platform));
  // Filtering out all the null entries
  errors = errors.filter((item) => { return item !== null; });

  if (errors.length > 0) {
    throw new Error('Error in .tldrrc configuration:\n' + errors.join('\n'));
  }
  return merged;
}

function validatePlatform(os) {
  let platform = require('./platform');
  if (os && !platform.isSupported(os)) {
    return 'Unsupported platform : ' + os;
  }
  return null;
}

function validateThemeItem(field, key) {
  let validValues = ['',
    'reset',
    'bold',
    'dim',
    'italic',
    'underline',
    'inverse',
    'hidden',
    'black',
    'red',
    'green',
    'yellow',
    'blue',
    'magenta',
    'cyan',
    'white',
    'gray',
    'bgBlack',
    'bgRed',
    'bgGreen',
    'bgYellow',
    'bgBlue',
    'bgMagenta',
    'bgCyan',
    'bgWhite'
  ];
  // TODO: change this to return all errors in a field
  for (let item in field) {
    if (field.hasOwnProperty(item)) {
      let tokens = field[item].replace(/\s+/g, '').split(',');
      for (let i = 0; i < tokens.length; i++) {
        if (validValues.indexOf(tokens[i]) < 0) {
          return 'Invalid theme value : ' + tokens[i] + ' in ' + key + ' theme';
        }
      }
    }
  }
  return null;
}

@@ -1601,18 +1601,20 @@
 ey) %7B%0A  
-le
+cons
 t validV
@@ -1966,129 +1966,70 @@
 ;%0A  
-// TODO: change this to return all errors in a field%0A  for (let item in field) %7B%0A    if (field.hasOwnProperty(item
+let errMsg = %5B%5D;%0A  for (let fieldKey of Object.keys(field
 )) %7B%0A
-  
     
@@ -2047,20 +2047,24 @@
 = field%5B
-item
+fieldKey
 %5D.replac
@@ -2097,49 +2097,33 @@
     
-  for (let i = 0; i %3C tokens.length; i++)
+tokens.forEach((token) =%3E
  %7B%0A 
@@ -2127,18 +2127,16 @@
 %7B%0A      
-  
 if (vali
@@ -2156,20 +2156,16 @@
 Of(token
-s%5Bi%5D
 ) %3C 0) %7B
@@ -2173,25 +2173,28 @@
         
-  return 
+errMsg.push(
 'Invalid
@@ -2221,12 +2221,8 @@
 oken
-s%5Bi%5D
  + '
@@ -2243,20 +2243,19 @@
 ' theme'
+)
 ;%0A
-  
       %7D%0A
@@ -2262,22 +2262,47 @@
     
+%7D);%0A
   %7D%0A  
-  %7D
+if (errMsg.length === 0) %7B
 %0A  
-%7D%0A
   re
@@ -2300,22 +2300,54 @@
  %7B%0A    return null;%0A
+  %7D%0A  return errMsg.join('%5Cn');%0A
 %7D%0A

Fix a theme item parsing todo