package com.sencorsta.rabs.ui;

import cn.hutool.core.io.FileUtil;
import cn.hutool.setting.Setting;
import com.sencorsta.rabs.AppMain;
import com.sencorsta.rabs.config.AppConfig;
import com.sencorsta.rabs.config.ConfigReader;
import com.sencorsta.rabs.obj.ThemeOption;
import com.sencorsta.rabs.ui.help.HelpWindow;
import com.sencorsta.rabs.ui.robot.OnePunchPanel;
import com.sencorsta.rabs.ui.robot.RobotPanel;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.FontUIResource;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Enumeration;

/**
 * @author daibin
 */
public class RootFrame extends JFrame {
	public static String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
	private static final String[] fontSizes = { "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
			"24", "25", "26" };
	String currFont = "";
	int currSize = 0;

	public RootFrame() {
		init();
	}

	public void init() {
		currFont = AppConfig.getInstance().getFont();
		currSize = AppConfig.getInstance().getFontSize();
		updateFont(new Font(currFont, Font.PLAIN, currSize));

		setTitle("Rabs V0.1");
		// 创建菜单栏
		JMenuBar menuBar = new JMenuBar();

		// 创建菜单
		JMenu fileMenu = new JMenu("文件");
		fileMenu.setMnemonic(KeyEvent.VK_F); // 设置 'F' 作为 File 菜单的助记符

		// 创建菜单项
		JMenuItem newMenuItem = new JMenuItem("加载配置文件");
		newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.ALT_DOWN_MASK));
		newMenuItem.addActionListener(e -> {
			JFileChooser fileChooser = new JFileChooser();
			File defaultPath = new File(ConfigReader.CONF_PATH);
			fileChooser.setCurrentDirectory(defaultPath);
			fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件", "properties");
			fileChooser.setFileFilter(filter);
			int result = fileChooser.showOpenDialog(this);
			if (result == JFileChooser.APPROVE_OPTION) {
				String selectedFilePath = fileChooser.getSelectedFile().getAbsolutePath();
				System.out.println("selectedFilePath = " + selectedFilePath);
				Setting setting = new Setting(selectedFilePath);
				AppConfig.getInstance().getSetting().clear();
				setting.getGroups().forEach(groups -> AppConfig.getInstance().getSetting().putAll(groups, setting.getMap(groups)));
				AppConfig.getInstance().getSetting().store();
				AppMain.update();
			}
		});

		JMenuItem openMenuItem = new JMenuItem("保存当前配置");
		openMenuItem.addActionListener(e -> {
			AppConfig.getInstance().saveAll();
		});
		JMenuItem saveMenuItem = new JMenuItem("配置另存为...");
		saveMenuItem.addActionListener(e -> {
			JFileChooser fileChooser = new JFileChooser();
			File defaultPath = new File(ConfigReader.CONF_PATH);
			fileChooser.setCurrentDirectory(defaultPath);
			FileNameExtensionFilter filter = new FileNameExtensionFilter("*.properties", "properties");
			fileChooser.setFileFilter(filter);
			int result = fileChooser.showSaveDialog(this);
			if (result == JFileChooser.APPROVE_OPTION) {
				File file = fileChooser.getSelectedFile();
				String selectedFilePath = file.getAbsolutePath();
				if (!FileUtil.exist(selectedFilePath)) {
					FileUtil.touch(selectedFilePath);
				}
				Setting setting = new Setting(selectedFilePath);
				setting.clear();
				AppConfig.getInstance().getSetting().getGroups().forEach(groups -> setting.putAll(groups, AppConfig.getInstance().getSetting().getMap(groups)));
				setting.store();
			}
		});
		JMenuItem exitMenuItem = new JMenuItem("退出");
		exitMenuItem.addActionListener(e -> dispose());

		// 将菜单项添加到菜单中
		fileMenu.add(newMenuItem);
		fileMenu.add(openMenuItem);
		fileMenu.add(saveMenuItem);
		fileMenu.addSeparator(); // 添加分隔符
		fileMenu.add(exitMenuItem);

		JMenu editMenu = new JMenu("编辑");
		JMenu viewMenu = new JMenu("视图");
		JMenu navigateMenu = new JMenu("导航");
		JMenu codeMenu = new JMenu("代码");
		JMenu windowMenu = new JMenu("窗口");

		initWindowMenu(windowMenu);

		JMenu helpMenu = new JMenu("帮助");
		JMenuItem aboutMenuItem = new JMenuItem("关于..");
		aboutMenuItem.addActionListener(e -> {
			HelpWindow helpWindow = new HelpWindow();
			helpWindow.setVisible(true);
		});
		helpMenu.add(aboutMenuItem);

		// 将菜单添加到菜单栏中
		menuBar.add(fileMenu);
		menuBar.add(editMenu);
		menuBar.add(viewMenu);
		menuBar.add(navigateMenu);
		menuBar.add(codeMenu);
		menuBar.add(windowMenu);
		menuBar.add(helpMenu);

		JLabel label = new JLabel();
		label.setText("");
		label.setForeground(new Color(121, 118, 118));
		menuBar.add(label);
		// 将菜单栏添加到 JFrame 中
		this.setJMenuBar(menuBar);

		JTabbedPane tabbedPane = new JTabbedPane();
		add(tabbedPane, BorderLayout.CENTER);

		RobotPanel panel1 = new RobotPanel();
		OnePunchPanel panel2 = new OnePunchPanel();

		tabbedPane.addTab("一拳超人", panel1);
		//tabbedPane.addTab("一键启动", panel2);
		tabbedPane.setTabPlacement(JTabbedPane.LEFT);
	}

	private void initWindowMenu(JMenu windowMenu) {
		windowMenu.setMnemonic(KeyEvent.VK_W);
		// 创建子菜单
		JMenu themeMenu = new JMenu("主题");
		initThemeMenu(themeMenu);
		// 将子菜单添加到菜单项中
		windowMenu.add(themeMenu);

		// 创建菜单项
		JMenu fontMenuItem = new JMenu("字体样式");
		for (int i = 0; i < fontNames.length; i++) {
			String fontName = fontNames[i];
			JMenuItem lightThemeMenuItem = new JMenuItem(fontName + "        [Abc 简体 繁體 123 !@#]");
			Font font = new Font(fontName, Font.PLAIN, currSize);
			currFont = font.getFontName();
			lightThemeMenuItem.setFont(font);
			lightThemeMenuItem.addActionListener((ActionEvent e) -> {
				updateFont(font);
				AppConfig.getInstance().getSetting().set("appFont", font.getName());
				AppConfig.getInstance().getSetting().store();
			});
			fontMenuItem.add(lightThemeMenuItem);
		}

		// 将菜单项添加到菜单中
		windowMenu.add(fontMenuItem);

		JMenu sizeMenuItem = new JMenu("字体大小");
		for (int i = 0; i < fontSizes.length; i++) {
			String fontName = fontSizes[i];
			JMenuItem lightThemeMenuItem = new JMenuItem(fontName + "        [Abc 简体 繁體 123 !@#]");
			Font font = new Font(currFont, Font.PLAIN, Integer.parseInt(fontName));
			lightThemeMenuItem.setFont(font);
			sizeMenuItem.add(lightThemeMenuItem);
			lightThemeMenuItem.addActionListener((ActionEvent e) -> {
				updateFont(font);
				AppConfig.getInstance().getSetting().set("appFontSize", font.getSize() + "");
				AppConfig.getInstance().getSetting().store();
			});
		}
		// 将菜单项添加到菜单中
		windowMenu.add(sizeMenuItem);
	}

	private void updateFont(Font font) {
		FontUIResource fontRes = new FontUIResource(font);
		for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
			Object key = keys.nextElement();
			Object value = UIManager.get(key);
			if (value instanceof FontUIResource) {
				UIManager.put(key, fontRes);
			}
		}
		SwingUtilities.updateComponentTreeUI(this);
	}

	private void initThemeMenu(JMenu themeMenu) {
		// 创建子菜单项
		JMenuItem lightThemeMenuItem = new JMenuItem("Light Theme");
		JMenuItem darkThemeMenuItem = new JMenuItem("Dark Theme");
		JMenuItem intellijThemeMenuItem = new JMenuItem("IntelliJ Theme");
		JMenuItem flatLafDarculaThemeMenuItem = new JMenuItem("Darcula Theme");
//		JMenuItem windowsThemeMenuItem = new JMenuItem("Windows Theme");
//		JMenuItem windowsClassicThemeMenuItem = new JMenuItem("Classic Theme");
		JMenuItem metalThemeMenuItem = new JMenuItem("Metal Theme");

		// 将子菜单项添加到子菜单中
		themeMenu.add(lightThemeMenuItem);
		themeMenu.add(darkThemeMenuItem);
		themeMenu.add(intellijThemeMenuItem);
		themeMenu.add(flatLafDarculaThemeMenuItem);
//		themeMenu.add(windowsThemeMenuItem);
//		themeMenu.add(windowsClassicThemeMenuItem);
		themeMenu.add(metalThemeMenuItem);

		// 为子菜单项添加事件监听器
		ActionListener actionListener = e -> {
			try {
				JMenuItem source = (JMenuItem) e.getSource();
				String text = source.getText();
				LookAndFeel newLookAndFeel = ThemeOption.getLookAndFeel(ThemeOption.fromString(text));
				UIManager.setLookAndFeel(newLookAndFeel);
				AppConfig.getInstance().getSetting().set("appTheme", text);
				AppConfig.getInstance().getSetting().store();
				SwingUtilities.updateComponentTreeUI(this);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		};
		lightThemeMenuItem.addActionListener(actionListener);
		darkThemeMenuItem.addActionListener(actionListener);
		intellijThemeMenuItem.addActionListener(actionListener);
		flatLafDarculaThemeMenuItem.addActionListener(actionListener);
//		windowsThemeMenuItem.addActionListener(actionListener);
//		windowsClassicThemeMenuItem.addActionListener(actionListener);
		metalThemeMenuItem.addActionListener(actionListener);
	}
}
