import { defineConfig, Plugin, ViteDevServer } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import * as path from 'path';
import * as fs from 'fs';
import formidable from 'formidable';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), vueJsx(), fileList()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src/'),
      '@meta2d': path.resolve(__dirname, '../meta2d.js/packages'),
    },
  },
  build: {
    outDir: 'v',
    rollupOptions: {
      output: {
        manualChunks: {
          monaco: [`monaco-editor`],
        },
      },
    },
  },
  server: {
    proxy: {
      '/image': 'https://2d.le5le.com/',
      '/file': 'https://2d.le5le.com/',
      '/api': 'https://2d.le5le.com/',
    },
  },
});

function fileList(): Plugin {
  return {
    name: 'vite-plugin-svg-png-files',
    configureServer(server: ViteDevServer) {
      server.middlewares.use((req, res, next) => {
        const url = req.url as string;

        if (
          (url.startsWith('/svg/') || url.startsWith('/png/')) &&
          url.endsWith('/')
        ) {
          const pwd = decodeURI(path.join(__dirname, 'public', url));
          const files = fs.readdirSync(pwd, {
            withFileTypes: true,
          });

          const list: {
            name: string;
            type?: string;
          }[] = [];
          for (const item of files) {
            if (item.isDirectory()) {
              list.push({ name: item.name, type: 'directory' });
            } else {
              list.push({ name: item.name });
            }
          }
          res.end(JSON.stringify(list));
        } else if (url === '/img' && req.method === 'POST') {
          const form = formidable({
            uploadDir: decodeURI(path.join(__dirname, 'public', '/img')),
            keepExtensions: true,
          });
          form.parse(req, (err, fields, files) => {
            if (!err) {
              res.end(
                JSON.stringify({ url: '/img/' + files.file.newFilename })
              );
            }
          });
        } else {
          next();
        }
      });
    },
  };
}
