const path = require('path')
const fs = require('fs')
const os = require('os')
const fsp = fs.promises

const homeDir = process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : os.homedir()

const profileDir = homeDir + path.sep + '.corellium'
const profilePath = profileDir + path.sep + 'profile.json'

const trialPath = profileDir + path.sep + 'trial.json'

async function updateProfile (options) {
  const currentProfile = {}
  try {
    // Load existing profile
    Object.assign(currentProfile, JSON.parse(await fsp.readFile(profilePath, { encoding: 'utf8' })))
  } catch (err) {
    if (err instanceof SyntaxError || err.code === 'ENOENT') {
      // reading json profile failed, make the new folder and file
      await fsp.mkdir(profileDir, { recursive: true })
    } else {
      // rethrow unhandled exceptions
      throw err
    }
  }

  // Write any new options, updating existing keys
  await fsp.writeFile(profilePath, JSON.stringify({ ...currentProfile, ...options }))
}

function writeTrialConfig (config) {
  fs.writeFileSync(trialPath, JSON.stringify(config))
}

function readTrialConfig () {
  return JSON.parse(fs.readFileSync(trialPath))
}

function readProfile () {
  if (!fs.existsSync(profilePath)) {
    throw new Error(`Profile not found at ${profilePath}. Try to login with "corellium login"`)
  }
  return JSON.parse(fs.readFileSync(profilePath))
}

async function deleteProfile () {
  if (!fs.existsSync(profilePath)) {
    throw new Error(`Profile not found at ${profilePath}`)
  }

  await fs.promises.unlink(profilePath)
  return profilePath
}

module.exports = {
  readProfile,
  deleteProfile,
  readTrialConfig,
  writeTrialConfig,
  updateProfile,
  profilePath
}
