import { Context } from 'koa'
import { Body, Get, Controller, Post, QueryParams, Ctx, QueryParam } from '@gem-mine/routing-controllers'

import * as path from 'path'
import * as fs from 'fs-extra'
import terminalExec from '../util/terminalExec'
import { db } from '../db'

@Controller('/component')
export default class {
  @Get('/')
  async getList(@QueryParams() { 
    component_id,
  }: {
    component_id: string
  }) {
    return {
      data: [
        await db.get('component')
          .find({
            component_id
          }).value()
      ].filter(Boolean)
    }
  }

  @Post('/')
  async createOne(@Body() modal: { component_id: string, token: string }) {
    const data = {
      component_id: modal.component_id,
      token: modal.token
    }
    await db.get('component')
      .updateOrAdd(data, 'component_id')
      .write()
    return {
      data
    }
  }

  @Get('/getPkgInfo') 
  async openExplorer(
    @QueryParam('path')
    _projectPath: string,
    @Ctx()
    context: Context
  ) {
    const projectPath = path.resolve(_projectPath)
    if (!fs.existsSync(projectPath)) {
      context.throw(400, '指定路径不存在')
    }
    const projectPkgPath = path.resolve(projectPath, './package.json')
    if (!fs.existsSync(projectPkgPath)) {
      context.throw(400, '指定路径不是NPM项目')
    }
    const pkgInfo = await fs.readJson(projectPkgPath, {
     throws: false
    })
    return pkgInfo
  }

  @Get('/terminalExec')
  async terminalExec(
    @QueryParam('path')
    _projectPath: string,
    @QueryParam('command')
    command: string,
    @Ctx()
    context: Context
  ) {
    const projectPath = path.resolve(_projectPath)
    if (!fs.existsSync(projectPath)) {
      context.throw(400, '指定路径不存在')
    }
    await terminalExec(command, {
      windowsHide: false,
      cwd: projectPath
    })
    return {}
  }
}
