import fs from 'fs'
import path from 'node:path'

interface IconfontJson {
  id: string;
  name: string;
  font_family: string;
  css_prefix_text: string;
  glyphs: {
    icon_id: string
    font_class: string
    unicode: string
    name: string
  }[];
}

const targetFile = path.resolve(__dirname, '../src/components/a-icon/iconfont.json')

const outPath = path.resolve(__dirname, '../src/components/a-icon')

function createTs(text: string) {
  const tsFile = path.resolve(outPath, 'iconfont.ts')
  console.log('正在生成文件：', tsFile)
  const tsContent = `export const icons = ${text.trim()} as const

export type IconName = (typeof icons.glyphs)[number]['font_class']
export const iconNames = icons.glyphs.map(it => it.font_class)

export interface IconGlyphs {
  icon_id: string
  name: string
  font_class: IconName
  unicode: string
  unicode_decimal: number
}

`
  fs.writeFileSync(tsFile, tsContent, {encoding: 'utf-8'})
}

function createCss(text: string) {
  const iconConfig = JSON.parse(text) as IconfontJson
  const cssFile = path.resolve(outPath, 'iconfont.css')
  console.log('正在生成文件：', cssFile)

  const time = new Date().getTime()
  let cssContent = `@font-face {
  font-family: "${iconConfig.font_family}"; /* 项目名称 ${iconConfig.name} */
  src: url('@/components/a-icon/iconfont.woff2?t=${time}') format('woff2'),
  url('@/components/a-icon/iconfont.woff?t=${time}') format('woff'),
  url('@/components/a-icon/iconfont.ttf?t=${time}') format('truetype');
}

.iconfont {
  font-family: "${iconConfig.font_family}", serif !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

`
  const iconsCss = iconConfig.glyphs.map(it => `.${iconConfig.css_prefix_text}${it.font_class}:before {
  content: "\\${it.unicode}";
}
`)
  cssContent += iconsCss.join('\n').trim()
  fs.writeFileSync(cssFile, cssContent + '\n', {encoding: 'utf-8'})

}

/**
 * 阿里图标处理器
 */
export default {
  process(data: VitePluginTypes.FileWatcherProcessParam) {
    const text = data.getContent()
    createTs(text)
    createCss(text)
  },
  isAccept(data: VitePluginTypes.FileWatcherAcceptParam) {
    return data.event === 'change' && !data.isDir && data.filePath === targetFile
  },
} as VitePluginTypes.FileWatcherOptions
