import RedmineIssueEventEmitterConfigLoader from '@app/event-emitter/configs/main-config';
import { readFileSync } from 'fs';
import { join } from 'path';
import { parse } from 'jsonc-parser';
import { AppConfig } from 'src/models/app-config.model';
import RedmineStatusesConfigLoader from './statuses.config';
import RedmineStatusChangesConfigLoader from './status-changes.config';
import RedmineEccmConfig from './eccm.config';
import RedmineCurrentUserRulesConfig from './current-user-rules.config';
import SimpleKanbanBoardConfig from './simple-kanban-board.config';
import CalendarEnhancer from './calendar-enhancer.config';

const redmineIssueEventEmitterConfig = RedmineIssueEventEmitterConfigLoader();
const redmineStatusesConfig = RedmineStatusesConfigLoader();
const redmineStatusChanges = RedmineStatusChangesConfigLoader();
const redmineEccm = RedmineEccmConfig();
const redmineCurrentUserRules = RedmineCurrentUserRulesConfig();
const simpleKanbanBoard = SimpleKanbanBoardConfig();
const calendarEnhancer = CalendarEnhancer();

let appConfig: AppConfig;

export default (): AppConfig => {
  if (appConfig) {
    return appConfig;
  }

  const userDefinedConfigPath = process.env['ELTEX_REDMINE_HELPER_CONFIG_PATH'];
  const defaultConfigPath = join('configs', 'main-config.jsonc');
  const configPath = userDefinedConfigPath || defaultConfigPath;

  const rawData = readFileSync(configPath, { encoding: 'utf-8' });

  const data = parse(rawData);

  appConfig = {
    ...data,
    redmineStatuses: redmineStatusesConfig,
    redmineIssueEventEmitterConfig: redmineIssueEventEmitterConfig,
    redmineStatusChanges: redmineStatusChanges,
    redmineEccm: redmineEccm,
    redmineCurrentUserRules: redmineCurrentUserRules,
    simpleKanbanBoard: simpleKanbanBoard,
    calendarEnhancer: calendarEnhancer,
  };

  return appConfig;
};
