import * as childProcess from 'child_process'
import * as fs from 'fs'

const platform = process.platform

let termExec

switch(platform) {
  case 'win32':
    termExec = function (command, options, callback) {
    
      command = 'start cmd /k "' + command + '"'
      //console.log(command)
      childProcess.exec(command, options, callback)
    }
    break
  default:
    const terminalBinsCandicates = [
      {
        path: '/usr/bin/xfce4-terminal',
        switch: '--command'
      },
      {
        path: '/usr/bin/xterm',
        switch: '-e'
      },
      {
        path: '/usr/bin/gnome-terminal',
        switch: '-e'
      },
      {
        path: '/usr/bin/konsole',
        switch: '-e'
      },
      {
        path: '/usr/bin/terminal',
        switch: '-e'
      }
    ]
    
    let terminalConf
    for (let i = 0; i < terminalBinsCandicates.length; i++) {
      let p = terminalBinsCandicates[i].path
      if (fs.existsSync(p)) {
        terminalConf = terminalBinsCandicates[i]
        break
      }
    }
    
    if (terminalConf !== undefined) {
      const terminalPath = terminalConf.path
      const terminalSwitch = terminalConf.switch
      
      termExec = function (command, options, callback) {
        if (command.indexOf('"')) {
          command = command.split('"').join('\\"')
        }
        command = terminalPath + ' ' + terminalSwitch + ' "' + command + '"'
        childProcess.exec(command, options, callback)
      }
    }
    else {
      console.log('Terminal is not found.')
      termExec = childProcess.exec
    }
}

export default termExec