package org.aohe.show;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.io.resource.UrlResource;
import com.github.sarxos.webcam.util.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.aohe.constant.SocketEnum;
import org.aohe.web.SocketUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 中文系统托盘弹出菜单不乱码。
 */
@Slf4j
public class TrayFrameUtf8 {

    public static void initSystemTrayUTF8() throws IOException {
        SocketUtils.start(SocketEnum.SCAN_SOCKET);
        //使用 JDialog 作为 JPopupMenu 载体
        JDialog jDialog = new JDialog();
        //关闭 JDialog 的装饰器
        jDialog.setUndecorated(true);
        //jDialog 作为 JPopupMenu 载体不需要多大的 size
        jDialog.setSize(1, 1);

        //创建 JPopupMenu
        //重写 firePopupMenuWillBecomeInvisible
        //消失后将绑定的组件一起消失
        JPopupMenu jPopupMenu = new JPopupMenu() {
            @Override
            public void firePopupMenuWillBecomeInvisible() {
                jDialog.setVisible(false);
                //log.info("JPopupMenu 不可见时绑定载体组件 jDialog 也不可见");
            }
        };
        jPopupMenu.setSize(100, 30);

        //添加菜单选项
        // JMenuItem exit = new JMenuItem(getUTF8String("退出"));
        JMenuItem exit = new JMenuItem("退出");
        exit.addActionListener(e -> {
            log.info("点击了退出选项");
            System.exit(0);
        });
        // JMenuItem showMainFrame = new JMenuItem(getUTF8String("显示主窗体"));
        JMenuItem showMainFrame = new JMenuItem("关于");
        showMainFrame.addActionListener(e -> {
            log.info("关于系统");
            JOptionPane.showMessageDialog(null, "AoHe 的扫描托盘程序");
            //显示窗口
        });

        JMenuItem startServiceItem = new JMenuItem("启动服务");
        JMenuItem stopServiceItem = new JMenuItem("停止服务");
        startServiceItem.setEnabled(false);
        stopServiceItem.setEnabled(true);
        startServiceItem.addActionListener(e ->{
            try {
                SocketUtils.start(SocketEnum.SCAN_SOCKET);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            startServiceItem.setEnabled(false);
            stopServiceItem.setEnabled(true);
            log.info("服务已启动");
            }
        );
        stopServiceItem.addActionListener(e -> {
            SocketUtils.safeStop(SocketEnum.SCAN_SOCKET);
            startServiceItem.setEnabled(true);
            stopServiceItem.setEnabled(false);
            log.info("服务已停止");
        });


        jPopupMenu.add(startServiceItem);
        jPopupMenu.add(stopServiceItem);

        jPopupMenu.add(showMainFrame);
        jPopupMenu.add(exit);
        URL url = ResourceUtil.getResource("../res/ah.png");
        String trayPng = "../res/ah.png";
        log.info("file:{}", url.getFile());
        Image image = Toolkit.getDefaultToolkit().getImage(url.getFile());
        // 创建系统托盘图标
        TrayIcon trayIcon = new TrayIcon(image, "Scan Program For AH");
        // 自动调整系统托盘图标大小
        trayIcon.setImageAutoSize(true);

        // 给托盘图标添加鼠标监听
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                //左键点击
                if (e.getButton() == 1) {
                    //显示窗口
                } else if (e.getButton() == 3 && e.isPopupTrigger()) {
                    // 右键点击弹出 JPopupMenu 绑定的载体以及 JPopupMenu
                    jDialog.setLocation(e.getX() + 5, e.getY() + 5 - jPopupMenu.getHeight());
                    // 显示载体
                    jDialog.setVisible(true);
                    // 在载体的 0,0 处显示对话框
                    jPopupMenu.show(jDialog, 0, 0);
                }
            }
        });
        // 添加托盘图标到系统托盘
        systemTrayAdd(trayIcon);
    }

    /**
     * 添加托盘图标到系统托盘中。
     *
     * @param trayIcon 系统托盘图标。
     */
    private static void systemTrayAdd(TrayIcon trayIcon) {
        // 将托盘图标添加到系统的托盘实例中
        SystemTray tray = SystemTray.getSystemTray();
        try {
            tray.add(trayIcon);
        } catch (AWTException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 字符串转 UTF-8 字符串
     *
     * @param str 要转换的字符串
     * @return UTF-8 编码的字符串
     */
    private static String getUTF8String(String str) {
        return new String(str.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
    }
}

