/*
 * COPYRIGHT (c) 1986-2020 Adobe Systems Incorporated.
 *
 * This source code contained herein is proprietary and
 * confidential information of Adobe Systems Incorporated
 * and is covered by the U.S. and other copyright and trade
 * secret protection.  Unauthorized adaptation, distribution,
 * use or display is prohibited and may be subject to civil
 * and criminal penalties.  Disclosure to others is prohibited.
 * For the terms and conditions of source code use refer to
 * your Adobe Systems Incorporated Source Code License Agreement.
 */

process.env["NODE_CONFIG_DIR"] = "./config/v16/";
var configMod = require('config');
var dbConfig = configMod.get('FMPS.dbConfig');
var webconfig = configMod.get('FMPS.webConfig');
var cronConfig = configMod.get('FMPS.cronConfig');
//var oktaConfig = config.get('FMPS.oktaConfig');
//var singleSignConfig = config.get('FMPS.singleSignConfig');
var ldapConfig = configMod.get('FMPS.ldapConfig');
var smtpConfig = configMod.get('FMPS.smtpConfig');
var appConfig = configMod.get('FMPS.appConfig');
var path = require('path');
var locks = require('locks');
var Enum = require('enum');
var messages = require('./messages');
var authmechanism36plain = "PLAIN";
var authmechanism36none = "NONE";
var checkheapdumtoload = exports.checkheapdumtoload = function () {
  try {
    return appConfig.get('enableHeapdump');
  } catch (e) {
    return false;
  }
};
var checkTokenExpiry = exports.checkTokenExpiry = function () {
  try {
    return webconfig.get('daysForTokenExpiryUserLogin');
  } catch (e) {
    return false;
  }
};
var compareAuthMechanism = exports.compareAuthMechanism = function (currentVal) {
  var plainL = authmechanism36plain.toLowerCase();
  var noneL = authmechanism36none.toLowerCase();
  var input = currentVal.toLowerCase();
  if (plainL.localeCompare(input) == 0 || noneL.localeCompare(input) == 0) {
    return true;
  }
  return false;
};
var getmongourl = exports.getmongourl = function () {
  try {
    var url;
    if (compareAuthMechanism(dbConfig.get('authMechanism'))) {
      url = process.env.MONGO_URL || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbName') + '?' + 'authSource' + '=' + dbConfig.get('authSource');
    } else {
      url = process.env.MONGO_URL || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbName') + '?' + 'authMechanism' + '=' + dbConfig.get('authMechanism') + '&' + 'authSource' + '=' + dbConfig.get('authSource');
    }
    //console.log("mongo url"+url);
    return url;
  } catch (e) {
    return "";
  }
};
var getlogQueueUrl = exports.getlogQueueUrl = function () {
  try {
    var url;
    if (compareAuthMechanism(dbConfig.get('authMechanism'))) {
      url = process.env.logQueueUrl || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('LogQueue') + '?' + 'authSource' + '=' + dbConfig.get('authSource');
    } else {
      url = process.env.logQueueUrl || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('LogQueue') + '?' + 'authMechanism' + '=' + dbConfig.get('authMechanism') + '&' + 'authSource' + '=' + dbConfig.get('authSource');
    }
    return url;
  } catch (e) {
    return "";
  }
};
var getmongoURLLog4J = exports.getmongoURLLog4J = function () {
  try {
    var url;
    if (compareAuthMechanism(dbConfig.get('authMechanism'))) {
      url = process.env.mongoURLLog4J || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbNameLog4j') + '?' + 'authSource' + '=' + dbConfig.get('authSource');
    } else {
      url = process.env.mongoURLLog4J || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbNameLog4j') + '?' + 'authMechanism' + '=' + dbConfig.get('authMechanism') + '&' + 'authSource' + '=' + dbConfig.get('authSource');
    }
    return url;
  } catch (e) {
    return "";
  }
};
var getmongoURLLOGS = exports.getmongoURLLOGS = function () {
  try {
    var url;
    if (compareAuthMechanism(dbConfig.get('authMechanism'))) {
      url = process.env.MONGO_URL || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbName') + '?' + 'authSource' + '=' + dbConfig.get('authSource');
    } else {
      url = process.env.MONGO_URL || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbName') + '?' + 'authMechanism' + '=' + dbConfig.get('authMechanism') + '&' + 'authSource' + '=' + dbConfig.get('authSource');
    }
    return url;
  } catch (e) {
    return "";
  }
};
var getmongoScheduler = exports.getmongoScheduler = function () {
  try {
    var url;
    if (compareAuthMechanism(dbConfig.get('authMechanism'))) {
      url = process.env.MONGO_Scheduler_URL_LOGS || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbNameQueue') + '?' + 'authSource' + '=' + dbConfig.get('authSource');
    } else {
      url = process.env.MONGO_Scheduler_URL_LOGS || 'mongodb://' + dbConfig.get('username') + ':' + dbConfig.get('password') + '@' + dbConfig.get('MONGO_HOST') + ':' + dbConfig.get('MONGO_PORT') + '/' + dbConfig.get('dbNameQueue') + '?' + 'authMechanism' + '=' + dbConfig.get('authMechanism') + '&' + 'authSource' + '=' + dbConfig.get('authSource');
    }
    return url;
  } catch (e) {
    return "";
  }
};
var getenableLogging = exports.getenableLogging = function () {
  try {
    return appConfig.get('enableLogging');
  } catch (e) {
    return false;
  }
};
var getenableLoggingMem = exports.getenableLoggingMEM = function () {
  try {
    return appConfig.get('enableLoggingMem');
  } catch (e) {
    return "INFO";
  }
};
var getenableheapDumpDebug = exports.getenableheapDumpDebug = function () {
  try {
    return appConfig.get('enableheapDumpDebug');
  } catch (e) {
    return false;
  }
};
var getListOfregistriesToShow = exports.getListOfregistriesToShow = function () {
  try {
    //this can be comma separated
    //https://www.npmjs.com/package/regedit
    return appConfig.get('listOfregistriesToShow');
  } catch (e) {

    var defaultRegistry = "HKCU\\Software\\" + appConfig.get('Company') + "\\" + "FrameMaker" + "\\" + appConfig.get('Version') + "\\" + "x64";

    return defaultRegistry;
  }
};
var getdisableAllMongoCache = exports.getdisableAllMongoCache = function () {
  try {
    return appConfig.get('disableAllMongoCache');
  } catch (e) {
    return false;
  }
};
var getConnectTimeOut = exports.getConnectTimeOut = function () {
  try {
    return dbConfig.get('connectTimeoutMS');
  } catch (e) {
    return 60000; //60sec
  }
};
var getsocketTimeoutMS = exports.getsocketTimeoutMS = function () {
  try {
    return dbConfig.get('socketTimeoutMS');
  } catch (e) {
    return 360000;
  }
};
var getkeepAlive = exports.getkeepAlive = function () {
  try {
    return dbConfig.get('keepAlive');
  } catch (e) {
    return 1;
  }
};
var getMaxApiLimitToThrottle = exports.getMaxApiLimitToThrottle = function () {
  try {
    return appConfig.get('apiLimitToThrottle');
  } catch (e) {
    return 2000;
  }
};
var getCleanWorkers = exports.getCleanWorkers = function () {
  try {
    if (process.env.doNotCleanWorker !== null || process.env.doNotCleanWorker !== undefined) {
      if (process.env.doNotCleanWorker === 'true') return true;else if (process.env.doNotCleanWorker === 'false') return false;
    } else return false;
  } catch (e) {
    return false;
  }
};

var config = exports.config = {
  defaultenumlist: null,
  cmsinfolist: ["", "ADOBE EXPERIENCE MANAGER", "DITA EXCHANGE", "DOCUMENTUM", "SHAREPOINT"],
  queuestatus: ["NOT_SCHEDULED", "RUNNING", "QUEUED", "COMPLETED"],
  outputformatslist: ["NOOUTPUT", "FM_PDF", "RH_WEBHELP", "RH_AIRHELP", "RH_HTMLHELP", "RH_FLASHHELP", "RH_ORACLEHELP", "RH_JAVAHELP", "RH_ECLIPSEHELP", "RH_EPUB", "RH_EPUB_3", "RH_MULTISCREEN", "RH_MOBI", "RH_APK", "RH_RESPONSIVEHELP", "RH_DPS", "RH_BASICHTML"],
  scheduleList: ["ONCE", "DAILY", "WEEKLY", "MONTHLY", "HOURLY"],
  userlist: ["OKTA", "ADMIN", "USER", "SINLESIGNON", "LDAP"],
  cleanWorkers: getCleanWorkers(),
  LimitMessageVal: appConfig.get('lengthOfLogMessage'),
  maxlengthofLoggerMessageTask: appConfig.get('lengthOfLogMessage') * 5,
  maxlengthofLoggerMessage: appConfig.get('lengthOfLogMessage'),
  queueMutex: {},
  scheduleTaskMutex: {},
  addTaskMutex: {},
  workerMutex: {},
  mongooseConnected: false,
  daysForTokenExpiryUserLogin: checkTokenExpiry(),
  workerqueueMutex: {},
  stsMutex: {},
  enableheapDumpDebug: getenableheapDumpDebug(),
  apiLimitToThrottle: getMaxApiLimitToThrottle(),
  ditaMutex: {},
  preMutex: {},
  postMutex: {},
  socketTimeoutMS: getsocketTimeoutMS(),
  connectTimeoutMS: getConnectTimeOut(),
  keepAlive: getkeepAlive(),
  LogType: new Enum([messages.messages.TASK, messages.messages.WORKER, messages.messages.QUEUELOG, messages.messages.GENERAL]),
  DefaultUser: process.env.DefaultUser || dbConfig.get('defaultUser'),
  DefaultId: "",
  DefaultPresetID: "",
  DefaultPresetName: messages.messages.DEFAULTPRESET,
  defaultstsid: "",
  defaultditaid: "",
  userCount: 0,
  logQueueT: {},
  logQueueQ: {},
  logQueueW: {},
  logQueueG: {},
  //  isMaster: process.env.isMaster || webconfig.get('isMaster'),
  logDB: process.env.LogQueue || dbConfig.get('LogQueue'),
  MaxNoOfLogs: process.env.MaxNoOfLogs || dbConfig.get('MaxNoOfLogs'),
  LogMonQueue: process.env.LogMonQueue || dbConfig.get('LogMonQueue'),
  logQueueUrl: getlogQueueUrl(),
  Defaultpassword: process.env.Defaultpassword || dbConfig.get('defaultPassword'),
  Defaultemail: process.env.Defaultemail || dbConfig.get('defaultEmail'),
  Defaultusertype: "ADMIN",
  // redistPort: process.env.redistPort || dbConfig.get('redistPort'),
  //redistHost: process.env.redistHost || dbConfig.get('redistHost'),
  logLevelUsed: process.env.logLevel || dbConfig.get('logLevel'),
  //useRedis: process.env.useRedis || dbConfig.get('useRedis'),
  DBNAME: process.env.DBNAME || dbConfig.get('dbName'),
  mongoURL: getmongourl(),
  mongoURLLog4J: getmongoURLLog4J(),
  mongoURLLOGS: getmongoURLLOGS(),
  mongoScheduler: getmongoScheduler(),
  port: process.env.PORT || dbConfig.get('MONGO_PORT'),
  schemaVersion: process.env.SCHEMA_VERSION || dbConfig.get('SCHEMA_VERSION'),
  apiVersion: process.env.SCHEMA_VERSION || webconfig.get('apiVersion'),
  HostingURL: process.env.HOSTING_URL || 'http://' + webconfig.get('host') + ':' + webconfig.get('port'),
  Hosting: process.env.HOST || webconfig.get('host'),
  useSSL: process.env.useSSL || webconfig.get('useSSL'),
  taskTimeOut: process.env.taskTimeOut || webconfig.get('taskTimeOut'), //in minutes
  runningtaskTimeOut: process.env.runningtaskTimeOut || webconfig.get('runningtaskTimeOut'), //in minutes
  maxTaskRetries: process.env.maxTaskRetries || webconfig.get('maxRetries'), //in minutes
  HostingProtocol: process.env.HostingProtocol || webconfig.get('protocol'),
  // cookieDomain: process.env.cookieDomain || webconfig.get('cookieDomain'),
  webport: process.env.WEBPORT || webconfig.get('port'),
  sslPort: process.env.sslPort || webconfig.get('sslPort'),
  HostingURLSSl: process.env.HOSTING_URL || 'https://' + webconfig.get('host') + ':' + webconfig.get('sslPort'),
  makeBackendAnonymousApiAvailable: 1,
  //https://cronexpressiondescriptor.azurewebsites.net/?expression=*%2F5+*+*+*+*&locale=en
  taskPollerCron: process.env.taskPollerCron || cronConfig.get('TaskPoller'),
  taskPollerFailedCron: process.env.taskPollerFailedCron || cronConfig.get('TaskPollerFailed'),
  taskPollerScheduledCron: process.env.taskPollerScheduledCron || cronConfig.get('TaskPollerScheduled'),
  //  WorkerConfigRefresh: process.env.WorkerConfigRefresh || cronConfig.get('WorkerConfigRefresh'),
  //daysToDeletion: process.env.daysToDeletion || cronConfig.get('daysToDeletion'),
  dbNameQueue: process.env.dbNameQueue || dbConfig.get('dbNameQueue'),
  dbNameLog4j: process.env.dbNameQueue || dbConfig.get('dbNameLog4j'),

  /*oktaURL: process.env.oktaURL || oktaConfig.get('oktaURL'),
  authorizequery: process.env.authorizequery || oktaConfig.get('authorizequery'),
  client_id: process.env.client_id || oktaConfig.get('client_id'),
  client_secret: process.env.client_id || oktaConfig.get('client_secret'),
  response_type: process.env.response_type || oktaConfig.get('response_type'),
  scope: process.env.scope || oktaConfig.get('scope'),
  redirect_uri: process.env.redirect_uri || oktaConfig.get('redirect_uri'),*/
  typeOfAuth: process.env.typeOfAuth || webconfig.get('typeOfAuth'),
  /* tokenquery: process.env.tokenquery || oktaConfig.get('tokenquery'),
   token_type: process.env.token_type || oktaConfig.get('token_type'),
   userinfo: process.env.userinfo || oktaConfig.get('userinfo'),
   validatequery: process.env.validatequery || oktaConfig.get('validatequery'),*/
  certPath: process.env.certPath || webconfig.get('certPath'),
  keyPath: process.env.keyPath || webconfig.get('keyPath'),

  /*idpurl: process.env.idpurl || singleSignConfig.get('idpurl'),
  idpissuer: process.env.idpissuer || singleSignConfig.get('idpissuer'),
  metadataurl: process.env.metadataurl || singleSignConfig.get('metadataurl'),
  metacert: process.env.metacert || singleSignConfig.get('metacert'),
  callbackUrl: process.env.skipreferrer || singleSignConfig.get('callbackUrl'),
  skipreferrer: process.env.callbackUrl || webconfig.get('skipreferrer'),*/

  ldapurl: process.env.ldapurl || ldapConfig.get('ldapurl'),
  baseDN: process.env.baseDN || ldapConfig.get('baseDN'),
  tlsOptions: process.env.tlsOptions || ldapConfig.get('tlsOptions'),
  domainName: process.env.domainName || ldapConfig.get('domainName'),

  smtphost: process.env.smtphost || smtpConfig.get('host'),
  smtpport: process.env.smtpport || smtpConfig.get('smtpport'),
  smtpusername: process.env.smtpusername || smtpConfig.get('username'),
  smtppassword: process.env.smtppassword || smtpConfig.get('password'),
  smtpusepassword: process.env.smtpusepassword || smtpConfig.get('requirePassword'),
  alertEmail: process.env.alertEmail || smtpConfig.get('alertEmail'),
  triggerAlertEmail: process.env.triggerAlertEmail || smtpConfig.get('triggerAlertEmail'),
  disableSMTP: process.env.disableSMTP || smtpConfig.get('disableSMTP'),
  companyPath: process.env.Company || appConfig.get('Company'),
  ProductPath: process.env.Product || appConfig.get('Product'),
  Nodelogs: process.env.Product || appConfig.get('NodeLogs'),
  appVersion: process.env.Version || appConfig.get('Version'),
  MaxMem: process.env.Version || appConfig.get('MaxMem'),
  listOfregistriesToShow: getListOfregistriesToShow(),
  serverConfiguration: messages.messages.RELEASE,
  serverConfigurationLogMem: null,
  serverConfigurationLogCpu: null,
  serverConfigurationLogApi: null,
  serverConfigurationLogHeap: null,
  serverConfigurationLogHeap2: null,
  serverConfigurationLogGC: null,
  serverConfigurationLog: null,
  serverConfigurationLogExp: null,
  serverConfigurationLogTaskMgr: null,
  serverConfigurationLogDIR: "",
  //  maxMinToAllowWorkDeletion: process.env.maxMinToAllowWorkDeletion || cronConfig.get('maxMinToAllowWorkDeletion') * 60000,
  defaultTimezone: process.env.defaultTimezone || webconfig.get('defaultTimezone'),
  generalmessage: "",
  queuemessage: "",
  taskmessage: "",
  workermessage: "",
  dbreadytouse: false,
  disableAllMongoCache: getdisableAllMongoCache(),
  enableHeapdump: checkheapdumtoload(),
  enableLogging: getenableLogging(),
  enableLoggingMEM: getenableLoggingMem()
};