'use strict'

const fs = require('fs')
const homedir = require('homedir')
const colors = require('colors/safe')

function createNofanDir () {
  return new Promise((resolve, reject) => {
    fs.mkdir(`${homedir()}/.nofan/`, () => {
      resolve()
    })
  })
}

function createJsonFile (filename, content) {
  return new Promise((resolve, reject) => {
    const filePath = `${homedir()}/.nofan/${filename}.json`
    fs.writeFile(filePath, JSON.stringify(content, null, 2), 'utf8', (e) => {
      if (e) reject(colors.red(`create file '${filePath}' failed`))
      else resolve()
    })
  })
}

function readJsonFile (filename) {
  return new Promise((resolve, reject) => {
    const filePath = `${homedir()}/.nofan/${filename}.json`
    fs.open(filePath, 'r', (e, fd) => {
      if (e) {
        if (e.code === 'ENOENT') {
          reject(colors.red(`file '${filePath}' does not exist`))
        }
        reject(colors.red(`read file '${filePath}' failed`))
      } else resolve(require(filePath))
    })
  })
}

async function getConfig () {
  try {
    return await readJsonFile('config')
  } catch (err) {
    console.log(err)
  }
}

async function getAccount () {
  try {
    return await readJsonFile('account')
  } catch (err) {
    return {}
  }
}

async function setConfig (config) {
  try {
    await createJsonFile('config', config)
  } catch (err) {
    console.log(err)
  }
}

async function setAccount (account) {
  try {
    await createJsonFile('account', account)
  } catch (err) {
    console.log(err)
  }
}

module.exports = {
  createNofanDir: createNofanDir,
  getConfig: getConfig,
  getAccount: getAccount,
  setConfig: setConfig,
  setAccount: setAccount
}

@@ -1004,30 +1004,24 @@
  %7D)%0A  %7D)%0A%7D%0A%0A
-async 
 function get
@@ -1028,34 +1028,24 @@
 Config () %7B%0A
-  try %7B%0A  
   return awa
@@ -1033,38 +1033,32 @@
 g () %7B%0A  return 
-await 
 readJsonFile('co
@@ -1068,51 +1068,8 @@
 g')%0A
-  %7D catch (err) %7B%0A    console.log(err)%0A  %7D%0A
 %7D%0A%0Aa
@@ -1178,38 +1178,32 @@
 eturn %7B%7D%0A  %7D%0A%7D%0A%0A
-async 
 function setConf
@@ -1218,32 +1218,16 @@
 ig) %7B%0A  
-try %7B%0A    await 
 createJs
@@ -1255,60 +1255,11 @@
 ig)%0A
-  %7D catch (err) %7B%0A    console.log(err)%0A  %7D%0A%7D%0A%0Aasync 
+%7D%0A%0A
 func
@@ -1292,24 +1292,8 @@
 %7B%0A  
-try %7B%0A    await 
 crea
@@ -1327,51 +1327,8 @@
 nt)%0A
-  %7D catch (err) %7B%0A    console.log(err)%0A  %7D%0A
 %7D%0A%0Am

remove try-catch