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';
import monacoEditorPlugin from 'vite-plugin-monaco-editor';
import viteCompression from "vite-plugin-compression"

// https://vitejs.dev/config/
export default defineConfig({
  // assetsInclude: ['**/*.glb'],
  plugins: [
    vue(),
    vueJsx(),
    // fileList(),
    monacoEditorPlugin({
      customDistPath: () => {
        return 'v/monacoeditorwork';
      },
      // publicPath: 'https://assets.le5lecdn.com/v/monacoeditorwork',
    }),
    viteCompression({
      threshold: 10240, // the unit is Bytes
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src/'),
      // '@meta2d': path.resolve(__dirname, '../meta2d.js/packages'),
      // '@2d-components': path.resolve(__dirname, '../2d-components/packages'),
      // '@meta3d': path.resolve(__dirname, '../meta3d.js'),
    },
  },
  build: {
    outDir: 'v',
    rollupOptions: {
      output: {
        manualChunks: {
          monaco: [`monaco-editor`],
        },
      },
    },
  },
  server: {
    proxy: {
      '/image': 'https://v.le5le.com/',
      '/file': 'https://v.le5le.com/',
      '/api': 'https://v.le5le.com/',
      '/v/material': 'https://v.le5le.com/',
      '/png': 'https://v.le5le.com/',
      '/svg': 'https://v.le5le.com/',
      // '/view': 'https://v.le5le.com/',
      '/api/tools':'https://v.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.startsWith('/material/')) &&
          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();
        }
      });
    },
  };
}
