import winston from 'winston'
import path from 'path'
import fs from 'fs'
import os from 'os'
import isDev from 'electron-is-dev'
import {app, dialog} from 'electron'

import FileHistory from './utils/file-history'
import KeyValueStore from './utils/key-value-store'

// Set up what to do on Uncaught Exceptions
process.on('uncaughtException', (error) => {
  const msg = error.message || error
  logger.error(`Uncaught Exception: ${error.stack}`)
  // TODO: save error to somewhere (in .txt) and recommend the user
  // to open an issue on the repo
  dialog.showErrorBox('Uncaught Exception:', msg)
  process.exit(1)
})

// Set up crash reporter or electron debug
if (isDev) {
  require('electron-debug')()
}

function logo (color) {
  const p = path.resolve(path.join(__dirname, 'img'))

  if (os.platform() === 'darwin') {
    return path.join(p, `icons/${color}.png`)
  }

  return path.join(p, `ipfs-logo-${color}.png`)
}

const ipfsAppData = (() => {
  const p = path.join(app.getPath('appData'), 'ipfs-station')

  if (!fs.existsSync(p)) {
    fs.mkdirSync(p)
  }

  return p
})()

const fileHistory = new FileHistory(path.join(ipfsAppData, 'file-history.json'))
const settingsStore = new KeyValueStore(path.join(ipfsAppData, 'config.json'))

if (!settingsStore.get('ipfsPath')) {
  const p = path.join(process.env.IPFS_PATH || (process.env.HOME || process.env.USERPROFILE), '.ipfs')
  settingsStore.set('ipfsPath', p)
}

// Sets up the Logger
const logger = winston.createLogger({
  format: winston.format.json(),
  transports: [
    new winston.transports.File({
      filename: 'error.log',
      level: 'error',
      handleExceptions: false
    }),
    new winston.transports.File({
      filename: 'combined.log',
      handleExceptions: false
    })
  ]
})

if (isDev) {
  logger.add(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.simple()
    ),
    handleExceptions: false
  }))
}

export default {
  logger: logger,
  fileHistory: fileHistory,
  settingsStore: settingsStore,
  logo: {
    ice: logo('ice'),
    black: logo('black')
  },
  // Will be replaced by a BrowserWindow instance.
  settingsWindow: {
    index: `file://${__dirname}/views/settings.html`,
    title: 'IPFS Station Settings',
    show: false,
    icon: logo('ice'),
    backgroundColor: '#252525',
    resizable: false,
    width: 450,
    height: 450
  },
  // Will be replaced by a Menubar instance.
  menubar: {
    index: `file://${__dirname}/views/menubar.html`,
    icon: logo('black'),
    tooltip: 'Your IPFS instance',
    preloadWindow: true,
    window: {
      resizable: false,
      skipTaskbar: true,
      width: 850,
      height: 400,
      backgroundColor: '#000000',
      webPreferences: {
        nodeIntegration: true,
        webSecurity: false
      }
    }
  }
}

@@ -265,361 +265,8 @@
 e'%0A%0A
-// Set up what to do on Uncaught Exceptions%0Aprocess.on('uncaughtException', (error) =%3E %7B%0A  const msg = error.message %7C%7C error%0A  logger.error(%60Uncaught Exception: $%7Berror.stack%7D%60)%0A  // TODO: save error to somewhere (in .txt) and recommend the user%0A  // to open an issue on the repo%0A  dialog.showErrorBox('Uncaught Exception:', msg)%0A  process.exit(1)%0A%7D)%0A%0A
 // S
@@ -571,166 +571,252 @@
 %0A%7D%0A%0A
-const ipfsAppData = (() =%3E %7B%0A  const p = path.join(app.getPath('appData'), 'ipfs-station')%0A%0A  if (!fs.existsSync(p)) %7B%0A    fs.mkdirSync(p)%0A  %7D%0A%0A  return p%0A%7D)(
+function ensurePath (path) %7B%0A  if (!fs.existsSync(path)) %7B%0A    fs.mkdirSync(path)%0A  %7D%0A%0A  return path%0A%7D%0A%0Aconst ipfsAppData = ensurePath(path.join(app.getPath('appData'), 'ipfs-station'))%0Aconst logsPath = ensurePath(path.join(ipfsAppData, 'logs')
 )%0A%0Ac
@@ -1312,16 +1312,36 @@
 ilename:
+ path.join(logsPath,
  'error.
@@ -1340,24 +1340,25 @@
  'error.log'
+)
 ,%0A      leve
@@ -1456,16 +1456,36 @@
 ilename:
+ path.join(logsPath,
  'combin
@@ -1491,16 +1491,17 @@
 ned.log'
+)
 ,%0A      
@@ -1741,16 +1741,542 @@
  %7D))%0A%7D%0A%0A
+function fatal (error) %7B%0A  logger.error(%60Uncaught Exception: $%7Berror.stack%7D%60)%0A%0A  dialog.showErrorBox(%0A    'Something wrong happened',%0A    %60Some unexpected error occurred and we couldn't handle it. Please check $%7Bpath.join(logsPath, 'error.log')%7D%60 +%0A    %60 for the latest logs and open an issue on https://github.com/ipfs-shipyard/ipfs-station/issues.%60%0A  )%0A%0A  process.exit(1)%0A%7D%0A%0A// Set up what to do on Uncaught Exceptions and Unhandled Rejections%0Aprocess.on('uncaughtException', fatal)%0Aprocess.on('unhandledRejection', fatal)%0A%0A
 export d

improve logging on uncaughExceptions and unhandledRejections (#570)