import * as path from 'path'
import * as fse from 'fs-extra'
import * as yml from 'js-yaml'

const configPath = path.resolve('./config')

const ENV_APP_NAME = 'APP_NAME'
const ENV_APP_DESCRIPTION = 'APP_DESCRIPTION'

const ENV_PORT = 'PORT'

function init (): { [key: string]: string } {
  const config: { [key: string]: string } = {}

  // Ensure config/index.json exists.
  const indexFilePath = path.resolve(configPath, 'index.yml')
  const indexFileExists = fse.existsSync(indexFilePath)
  if (!indexFileExists) {
    console.error(`Error: Missing file config/index.yml. File searched for at path: ${indexFilePath}`)
    return {}
  }

  // Set general config settings.
  const indexConfig = yml.safeLoad(fse.readFileSync(indexFilePath).toString())

  const processPort = process.env[ENV_PORT] !== undefined ? process.env[ENV_PORT] : undefined
  config[ENV_PORT] = processPort || indexConfig.port

  config[ENV_APP_NAME] = indexConfig.app_name
  config[ENV_APP_DESCRIPTION] = indexConfig.app_description

  return config
}

export {
  init,
  ENV_APP_NAME,
  ENV_APP_DESCRIPTION,
  ENV_PORT
}
