import { Body, Controller, Post, Get, Param, QueryParam } from '@gem-mine/routing-controllers'

const os = require('os')
const path = require('path')
const fs = require('fs-extra')
const currentOs = os.platform()
const child_process = require('child_process')

const openExplorer = path => {
  if (currentOs === 'win32') {
    openExplorerWindows(path)
  } else if (currentOs === 'darwin') {
    openExplorerMac(path)
  } else {
    openExplorerLinux(path)
  }
}

const openExplorerWindows = path => {
  child_process.execSync(`cd ${path} && explorer .`)
}

const openExplorerMac = path => {
  child_process.execSync(`open ${path}`)
}

const openExplorerLinux = path => {
  child_process.execSync(`nautilus ${path}`)
}

@Controller('/os')
export default class {
  @Post('/openExplorer')
  async openExplorer(@Body() modal: { path: string }) {
    const _path = path.resolve(modal.path)
    if (!fs.existsSync(_path)) {
      return {
        success: false,
        message: '文件夹打开失败，请检查本地文件夹路径是否存在！'
      }
    }
    try {
      openExplorer(_path)
      return {
        success: true
      }
    } catch (error) {
      return {
        success: true,
        message: '文件夹打开失败！'
      }
    }
  }

  @Post('/gitLink')
  async gitLink(@Body() modal: { path: string, remote: string }) {
    const { path, remote } = modal
    if (!fs.existsSync(path)) {
      return {
        success: false,
        message: '请检查本地文件夹路径是否存在！'
      }
    }
    try {
      child_process.execSync(`git remote add origin ${remote}`, {
        cwd: path,
        stdio: ['pipe', 'pipe', 'pipe'],
        windowsHide: true
      })
      return {
        success: true
      }
    } catch (error) {
      return {
        success: false,
        message: 'git 关联失败！'
      }
    }
  }

  @Get('/gitLink/:path')
  async getGitLink(@Param('path') _path: string) {
    const cwd = path.resolve(decodeURIComponent(_path))
    if (!fs.existsSync(cwd)) {
      return {
        success: false,
        message: '请检查本地文件夹路径是否存在！'
      }
    }
    try {
      const url = child_process.execSync('git remote get-url origin', {
        cwd: cwd,
        stdio: ['pipe', 'pipe', 'pipe'],
        windowsHide: true
      }).toString()
      return {
        url,
        success: true
      }
    } catch (error) {
      return {
        success: false,
        message: 'git remote 获取失败！'
      }
    }
  }

  @Get('/uiVersion')
  async uiVersion(@QueryParam('path') _path: string, @QueryParam('ui') ui: string) {
    const cwd = path.resolve(_path)
    if (!fs.existsSync(cwd)) {
      return {
        success: false,
        message: '请检查本地文件夹路径是否存在！'
      }
    }
    try {
      const version = require(`${cwd}/node_modules/${ui}/package.json`).version
      return {
        version,
        success: true
      }
    } catch (error) {
      return {
        success: false,
        message: `${ui} 版本获取失败！`
      }
    }
  }
}
