import path from 'path'
import chalk from 'chalk'
import ora from 'ora'
import fs from 'fs'
import { openInBrowser } from '../../utils/other'
import axios from 'axios'
import ejs from 'ejs'
import Server from '../../server/app'

function launchServer(callback: any) {
  const server = new Server()
  server.router.get('/', (ctx: any) => {
    callback(ctx)
  })
  server.launch().then(() => {
    const url = `http://localhost:${server.port}/`
    console.log(`服务启动成功!`)
    console.log(`CDN列表访问地址: ${chalk.green(url)}`)
    openInBrowser(url)
  })
}

// 过滤掉不需要的资源
function filterUrls(list: any) {
  list['@syman/ark-ui'] = list['@syman/ark-ui'].filter(
    (url: string) =>
      url.endsWith('ark.min.js') ||
      url.endsWith('ark-ui.css') ||
      url.endsWith('iconfont.css')
  )
  list['@syman/ark-ui-bcl'] = list['@syman/ark-ui-bcl'].filter(
    (url: string) =>
      url.endsWith('ark.bcl.min.js') || url.endsWith('ark.bcl.min.css')
  )
  list['@syman/burgeon-r3'] = list['@syman/burgeon-r3'].filter(
    (url: string) => url.endsWith('min.js') || url.endsWith('min.css')
  )
  return list
}

async function listOSS() {
  const spinner = ora('正在请求远程cdn数据...').start()

  axios
    .get('https://ark-font.oss-cn-hangzhou.aliyuncs.com/oss.json') // 获取cdn列表
    .then((res) => {
      const result = res.data

      if (result.code === 200) {
        // 渲染html模板
        const templatePath = path.join(
          __dirname,
          '../../assets/ejs-template/oss-cdn.html'
        )
        const html = ejs.render(fs.readFileSync(templatePath).toString(), {
          OSS_LIST: JSON.stringify(filterUrls(result.data)),
        })
        spinner.succeed('准备启动cdn列表界面')

        // 启动服务预览html
        launchServer((ctx: any) => {
          ctx.type = 'html'
          ctx.body = html
        })
      }
    })
    .catch((err) => {
      spinner.stop()
      console.log('', err)
    })
}

export default listOSS
