import express from 'express'
import path from 'path'
import bodyParser from 'body-parser'
import * as fs from 'fs'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const startup = false

const enter = `
import { modulesParse } from '../helper'

const { ctx, promise } = modulesParse(
  import.meta.glob(['./*.ts', '!./index.ts'])
)

export default ctx
export { promise }

`
const writeFile = (path, content) =>
  new Promise((resolve, reject) => {
    fs.writeFile(path, content, err => {
      if (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })

const langDir = path.join(__dirname, '../src/lang')
const writeLang = (name, lang) => {
  const dir = path.join(langDir, name)
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir)
  }

  return Promise.all([
    writeFile(path.join(dir, 'index.ts'), enter),
    ...Object.entries(lang).map(([name, content]) =>
      writeFile(
        path.join(dir, `${name}.ts`),
        `export default ${JSON.stringify(content, null, 4)}`
      )
    )
  ])
}

export async function createServer(port) {
  if (startup) {
    return
  }

  const app = express()
  app.use('/dev', bodyParser.json())
  app.use('/dev', bodyParser.urlencoded({ extended: false }))

  app.post('/dev/langs', async function (req, res) {
    const langs = req.body
    const handlers = Object.entries(langs).map(([name, lang]) =>
      writeLang(name, lang)
    )
    Promise.all(handlers)
      .then(() => res.json({ ok: true }))
      .catch(() => res.json({ ok: false }))
  })
  app.listen(port)
  console.log('语言编辑已开启')
}
