package com.axis.innovators.box.register;


import com.axis.innovators.box.AxisInnovatorsBox;
import com.axis.innovators.box.gui.LoadIcon;
import com.axis.innovators.box.gui.WindowsJDialog;
import com.axis.innovators.box.plugins.PluginDescriptor;
import com.axis.innovators.box.plugins.PluginLoader;
import com.axis.innovators.box.plugins.PluginPyLoader;
import com.axis.innovators.box.util.PythonResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.tzd.lm.LM;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用于注册设置项的类
 * @author tzdwindows 7
 */
public class RegistrationSettingsItem extends WindowsJDialog {
    private static final List<RegistrationSettingsItem> registrationSettingsItemList = new ArrayList<>();
    private static final Logger logger = LogManager.getLogger(RegistrationSettingsItem.class);
    private static RegistrationTopic registrationTopic;
    private final List<UUID> uuidList = new ArrayList<>();
    private final List<String> registeredNameList = new ArrayList<>();
    private final List<JPanel> tabbedPanesSettings = new ArrayList<>();
    private final List<String> titleList = new ArrayList<>();
    private final List<Icon> iconList = new ArrayList<>();
    private final List<String> tipList = new ArrayList<>();
    private boolean isEmpty = true;
    private final AxisInnovatorsBox mainWindow;

    static {
        RegistrationSettingsItem registrationSettingsItem = new RegistrationSettingsItem();
        JPanel pluginPanel = createPluginSettingsPanel();
        JPanel generalPanel = createGeneralSettingsPanel();
        JPanel aboutPanel = createAboutPanel();
        JPanel themePanel = createThemePanel();

        registrationSettingsItem.addSettings(
                pluginPanel, language.getText("settings.1.title"),
                null, language.getText("settings.1.tip"), "system:settings_plugins_item"
        );
        registrationSettingsItem.addSettings(
                generalPanel, language.getText("settings.2.title"),
                null, language.getText("settings.2.tip"), "system:settings_appearance_item"
        );
        registrationSettingsItem.addSettings(
                aboutPanel, language.getText("settings.3.title"),
                null, language.getText("settings.3.tip"), "system:settings_information_item"
        );
        registrationSettingsItem.addSettings(
                themePanel, language.getText("settings.4.title"),
                null, language.getText("settings.4.tip"), "system:settings_theme_item"
        );

        registrationSettingsItemList.add(
                registrationSettingsItem
        );
    }

    public static void overloading() {
        language = LanguageManager.getLoadedLanguages();
        registrationSettingsItemList.clear();
        RegistrationSettingsItem registrationSettingsItem = new RegistrationSettingsItem();
        JPanel pluginPanel = createPluginSettingsPanel();
        JPanel generalPanel = createGeneralSettingsPanel();
        JPanel aboutPanel = createAboutPanel();
        JPanel themePanel = createThemePanel();

        registrationSettingsItem.addSettings(
                pluginPanel, language.getText("settings.1.title"),
                null, language.getText("settings.1.tip"), "system:settings_plugins_item"
        );
        registrationSettingsItem.addSettings(
                generalPanel, language.getText("settings.2.title"),
                null, language.getText("settings.2.tip"), "system:settings_appearance_item"
        );
        registrationSettingsItem.addSettings(
                aboutPanel, language.getText("settings.3.title"),
                null, language.getText("settings.3.tip"), "system:settings_information_item"
        );
        registrationSettingsItem.addSettings(
                themePanel, language.getText("settings.4.title"),
                null, language.getText("settings.4.tip"), "system:settings_theme_item"
        );

        registrationSettingsItemList.add(
                registrationSettingsItem
        );

        AxisInnovatorsBox.getMain().getMainWindow().showSettings();
    }

    private static JPanel createThemePanel() {
        JPanel themePanel = new JPanel(new BorderLayout());

        RegistrationTopic registrationTopic = getRegistrationTopic();

        if (registrationTopic.isEmpty()) {
            themePanel.add(new JLabel(language.getText("settings.4.no_theme"), SwingConstants.CENTER), BorderLayout.CENTER);
            return themePanel;
        }

        // 创建搜索栏
        JPanel searchPanel = new JPanel(new BorderLayout());
        JTextField searchField = new JTextField();
        JButton searchButton = new JButton(language.getText("settings.4.search"));
        searchPanel.add(searchField, BorderLayout.CENTER);
        searchPanel.add(searchButton, BorderLayout.EAST);
        searchPanel.setVisible(false);

        // 将搜索栏添加到主题面板的顶部
        themePanel.add(searchPanel, BorderLayout.NORTH);

        DefaultListModel<JPanel> listModel = new DefaultListModel<>();
        JList<JPanel> themeList = new JList<>(listModel);

        themeList.setCellRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                JPanel itemPanel = (JPanel) value;

                if (registrationTopic.isLoading(registrationTopic.getRegisteredNameList().get(index))) {
                    itemPanel.setEnabled(false);
                    itemPanel.setBackground(Color.LIGHT_GRAY);
                } else {
                    itemPanel.setEnabled(true);
                    itemPanel.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
                }

                return itemPanel;
            }
        });

        // 监听键盘事件
        themeList.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_F) {
                    searchPanel.setVisible(true);
                    searchField.requestFocusInWindow();
                }
            }
        });

        searchButton.addActionListener(e -> {
            String searchText = searchField.getText().trim().toLowerCase();
            if (searchText.isEmpty()) {
                JOptionPane.showMessageDialog(null,
                        language.getText("settings.4.search_empty"),
                        language.getText("settings.4.search_empty_title"), JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            for (int i = 0; i < registrationTopic.getTopicsClasses().size(); i++) {
                String topicName = registrationTopic.getTopicsName().get(i).toLowerCase();
                if (topicName.contains(searchText)) {
                    themeList.setSelectedIndex(i);
                    themeList.ensureIndexIsVisible(i);
                    return;
                }
            }

            JOptionPane.showMessageDialog(null,
                    language.getText("settings.4.search_not_found"),
                    language.getText("settings.4.search_not_found_title"), JOptionPane.INFORMATION_MESSAGE);
        });

        themeList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = themeList.locationToIndex(e.getPoint());
                    if (index >= 0) {
                        if (registrationTopic.isLoading(registrationTopic.getRegisteredNameList().get(index))) {
                            JOptionPane.showMessageDialog(null, language.getText("settings.4.loading"),
                                    language.getText("settings.4.loading_title"), JOptionPane.INFORMATION_MESSAGE);
                            return;
                        }
                        loadTheme(registrationTopic, index, themeList);
                    }
                }
            }
        });

        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem loadMenuItem = new JMenuItem(language.getText("settings.4.load"));
        loadMenuItem.addActionListener(e -> {
            int index = themeList.getSelectedIndex();
            if (index >= 0) {
                if (registrationTopic.isLoading(registrationTopic.getRegisteredNameList().get(index))) {
                    JOptionPane.showMessageDialog(null, language.getText("settings.4.loading"),
                            language.getText("settings.4.loading_title"), JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                loadTheme(registrationTopic, index, themeList);
            }
        });
        popupMenu.add(loadMenuItem);

        themeList.setComponentPopupMenu(popupMenu);

        for (int i = 0; i < registrationTopic.getTopicsClasses().size(); i++) {
            JPanel itemPanel = new JPanel(new BorderLayout());
            itemPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

            JLabel iconLabel = new JLabel(registrationTopic.getIconList().get(i));
            itemPanel.add(iconLabel, BorderLayout.WEST);

            JPanel infoPanel = new JPanel(new GridLayout(0, 1));
            String tip = registrationTopic.getTipList().get(i);
            if (tip == null) {
                tip = registrationTopic.getTopicsClassesLookAndFeel().get(i).getName();
            }
            infoPanel.add(new JLabel(language.getText("settings.4.info") + tip));
            infoPanel.add(new JLabel(language.getText("settings.4.info.1") + registrationTopic.getTopicsName().get(i)));
            infoPanel.add(new JLabel(language.getText("settings.4.info.2") + registrationTopic.getTipList().get(i)));
            infoPanel.add(new JLabel(language.getText("settings.4.info.3") + registrationTopic.getRegisteredNameList().get(i)));
            itemPanel.add(infoPanel, BorderLayout.CENTER);

            listModel.addElement(itemPanel);
        }

        JScrollPane scrollPane = new JScrollPane(themeList);
        themePanel.add(scrollPane, BorderLayout.CENTER);

        return themePanel;
    }

    /**
     * 加载主题
     */
    private static void loadTheme(RegistrationTopic registrationTopic, int index, JList<JPanel> themeList) {
        String themeClass = registrationTopic.getTopicsClasses().get(index);
        String themeName = registrationTopic.getTopicsName().get(index);
        String registeredName = registrationTopic.getRegisteredNameList().get(index);
        try {
            if (themeClass != null) {
                UIManager.setLookAndFeel(themeClass);
            } else {
                LookAndFeel theme = registrationTopic.getTopicsClassesLookAndFeel().get(index);
                UIManager.setLookAndFeel(theme);
            }
            JOptionPane.showMessageDialog(null, language.getText("settings.4.load_theme_success")
                            + themeName + language.getText("settings.4.load_theme_success.2"),
                    language.getText("settings.4.load_theme_success.3"), JOptionPane.INFORMATION_MESSAGE);
            registrationTopic.setLoading(registeredName);
            themeList.repaint();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, language.getText("settings.4.load_theme_error")
                            + e.getMessage(),
                    language.getText("settings.4.load_theme_error.title"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private static RegistrationTopic getRegistrationTopic() {
        return registrationTopic;
    }

    private static JPanel createAboutPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JTextArea infoArea = new JTextArea();
        infoArea.setEditable(false);
        infoArea.setLineWrap(true);
        infoArea.setWrapStyleWord(true);
        infoArea.append(language.getText("settings.3.infoArea.1") + AxisInnovatorsBox.getVersion() + "\n\n");
        infoArea.append(language.getText("settings.3.infoArea.2") + "\n");
        for (String author : AxisInnovatorsBox.getAuthor()) {
            infoArea.append("• " + author + "\n");
        }

        panel.add(new JScrollPane(infoArea), BorderLayout.CENTER);
        return panel;
    }

    private static class FontChooser extends JPanel {
        private final JComboBox<String> fontFamilyCombo;
        private final JSpinner fontSizeSpinner;

        public FontChooser(Font currentFont) {
            setLayout(new GridLayout(2, 2, 5, 5));

            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fontFamilies = ge.getAvailableFontFamilyNames();
            fontFamilyCombo = new JComboBox<>(fontFamilies);
            fontFamilyCombo.setSelectedItem(currentFont.getFamily());

            SpinnerNumberModel sizeModel = new SpinnerNumberModel(
                    currentFont.getSize(), 8, 48, 1
            );
            fontSizeSpinner = new JSpinner(sizeModel);

            add(new JLabel("字体："));
            add(fontFamilyCombo);
            add(new JLabel("大小："));
            add(fontSizeSpinner);
        }

        public Font getSelectedFont() {
            return new Font(
                    (String) fontFamilyCombo.getSelectedItem(),
                    Font.PLAIN,
                    (Integer) fontSizeSpinner.getValue()
            );
        }
    }

    private static void applyThemeColor(Color color) {
        UIManager.put("Panel.background", color);
        UIManager.put("TabbedPane.background", color);

        SwingUtilities.updateComponentTreeUI(AxisInnovatorsBox.getMain().getMainWindow());
    }

    private static JPanel createPluginSettingsPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        String[] columns = {
                language.getText("settings.1.columns.0"),
                language.getText("settings.1.columns.1"),
                language.getText("settings.1.columns.2"),
                language.getText("settings.1.columns.3")
        };

        List<Object[]> pluginData = new ArrayList<>();

        for (PluginDescriptor plugin : PluginLoader.getLoadedPlugins()) {
            pluginData.add(new Object[]{
                    "Java",
                    plugin.getName(),
                    String.join(", ", plugin.getSupportedVersions()),
                    plugin.getDescription()
            });
        }

        for (PluginPyLoader.PyPluginDescriptor plugin : PluginPyLoader.getLoadedPlugins().values()) {
            pluginData.add(new Object[]{
                    "Python",
                    plugin.getName(),
                    "N/A",
                    plugin.getLastResult().getOutput()
            });
        }

        DefaultTableModel model = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        for (Object[] row : pluginData) {
            model.addRow(row);
        }

        JTable table = new JTable(model);
        table.setRowHeight(30);
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int selectedRow = table.getSelectedRow();
                    if (selectedRow >= 0) {
                        String pluginType = (String) model.getValueAt(selectedRow, 0);
                        String pluginId = "";

                        try {
                            if ("Java".equals(pluginType)) {
                                PluginDescriptor selectedPlugin = PluginLoader.getLoadedPlugins().get(selectedRow);
                                showPluginDetails(selectedPlugin);
                            }
                        } catch (Exception ex) {
                            logger.error("Failed to show plugin details [ID:{}]", pluginId, ex);
                            JOptionPane.showMessageDialog(panel,
                                    "插件信息加载失败：" + ex.getMessage(),
                                    "系统错误",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createTitledBorder(language.getText("settings.1.scrollPane")));
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }
    private static void showPluginDetails(PluginDescriptor plugin) {
        JDialog dialog = new JDialog(AxisInnovatorsBox.getMain().getMainWindow(), "插件详细信息", true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(AxisInnovatorsBox.getMain().getMainWindow());

        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JPanel iconPanel = new JPanel();

        ImageIcon icon = LoadIcon.loadIcon(plugin.getInstance().getClass(), plugin.getIcon(), 64);
        JLabel iconLabel = new JLabel(icon);
        iconPanel.add(iconLabel);
        mainPanel.add(iconPanel, BorderLayout.WEST);

        JPanel infoPanel = new JPanel(new GridLayout(0, 1, 5, 5));
        infoPanel.setBorder(BorderFactory.createTitledBorder("插件信息"));

        infoPanel.add(new JLabel("插件名称: " + plugin.getName()));

        String classFilePath = plugin.getClass().getResource(plugin.getClass().getSimpleName() + ".class").toString();
        if (classFilePath.startsWith("jar:")) {
            classFilePath = classFilePath.substring("jar:".length(), classFilePath.indexOf("!"));
        } else if (classFilePath.startsWith("file:")) {
            classFilePath = classFilePath.substring("file:".length(), classFilePath.indexOf(plugin.getClass().getSimpleName() + ".class"));
        }

        JTextArea locationTextArea = new JTextArea("插件位置: " + classFilePath);
        locationTextArea.setLineWrap(true);
        locationTextArea.setWrapStyleWord(true);
        locationTextArea.setEditable(false);
        locationTextArea.setBackground(infoPanel.getBackground());
        infoPanel.add(new JScrollPane(locationTextArea));

        infoPanel.add(new JLabel("主类: " + plugin.getInstance().getClass()));
        if (plugin.getTransformers() != null) {
            infoPanel.add(new JLabel("核心转换器: " + plugin.getTransformers()));
        } else {
            infoPanel.add(new JLabel("核心转换器: 无"));
        }
        infoPanel.add(new JLabel("描述: " + plugin.getDescription()));

        mainPanel.add(infoPanel, BorderLayout.CENTER);

        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(closeButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(mainPanel);
        dialog.setVisible(true);
    }

    private static JPanel createGeneralSettingsPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel(language.getText("settings.2.color")), gbc);

        JButton colorBtn = new JButton(language.getText("settings.2.colorBtn"));
        colorBtn.addActionListener(e -> {
            Color color = JColorChooser.showDialog(panel,
                    language.getText("settings.2.colorBtn.color"), Color.WHITE);
            if (color != null) {
                applyThemeColor(color);
            }
        });
        gbc.gridx = 1;
        panel.add(colorBtn, gbc);

        // 界面字体设置
        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(new JLabel(language.getText("settings.2.font")), gbc);

        JButton fontBtn = new JButton(language.getText("settings.2.fontBtn"));
        fontBtn.addActionListener(e -> {
            Font currentFont = UIManager.getFont("Label.font");
            FontChooser fontChooser = new FontChooser(currentFont);
            int result = JOptionPane.showConfirmDialog(
                    panel,
                    fontChooser,
                    language.getText("settings.2.showConfirmDialog"),
                    JOptionPane.OK_CANCEL_OPTION
            );

            if (result == JOptionPane.OK_OPTION) {
                applyUIFont(fontChooser.getSelectedFont());
            }
        });
        gbc.gridx = 1;
        panel.add(fontBtn, gbc);

        // CUDA 设置
        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(new JLabel(language.getText("settings.2.cuda")), gbc);

        JCheckBox cudaCheckBox = new JCheckBox(language.getText("settings.2.cudaCheckBox"), LM.CUDA);
        cudaCheckBox.addActionListener(e -> {
            boolean useCUDA = cudaCheckBox.isSelected();
            LM.CUDA = useCUDA;
            logger.info("CUDA加速设置已更新: " + (useCUDA ? "启用" : "禁用"));

            try {
                LM.loadLibrary(useCUDA);
                logger.info("AI推理库已重新加载");
            } catch (Exception ex) {
                logger.error("无法重新加载AI推理库", ex);
                JOptionPane.showMessageDialog(panel, language.getText("settings.2.cuda.error"),
                        language.getText("settings.2.cuda.error.1"), JOptionPane.ERROR_MESSAGE);
            }
        });
        gbc.gridx = 1;
        panel.add(cudaCheckBox, gbc);

        // 语言设置
        gbc.gridy++;
        gbc.gridx = 0;
        panel.add(new JLabel(language.getText("settings.2.language")), gbc);

        List<LanguageManager.Language> languages = LanguageManager.getLanguages();
        String[] languageNames = languages.stream()
                .map(LanguageManager.Language::getLanguageName)
                .toArray(String[]::new);

        JComboBox<String> languageComboBox = new JComboBox<>(languageNames);
        if (LanguageManager.getLoadedLanguages() != null) {
            languageComboBox.setSelectedItem(LanguageManager.getLoadedLanguages().getLanguageName());
        } else {
            languageComboBox.setSelectedItem(language.getText("settings.2.language.error"));
        }
        languageComboBox.addActionListener(e -> {
            String selectedLanguageName = (String) languageComboBox.getSelectedItem();
            LanguageManager.Language selectedLanguage = LanguageManager.getLanguage(selectedLanguageName);
            if (selectedLanguage != null) {
                LanguageManager.loadLanguage(selectedLanguage.getRegisteredName());
                logger.info("语言已切换为: " + selectedLanguage.getLanguageName());
                AxisInnovatorsBox.getMain().reloadAllWindow();

            } else {
                logger.error("无法切换语言: " + selectedLanguageName);
            }
        });
        gbc.gridx = 1;
        panel.add(languageComboBox, gbc);

        return panel;
    }

    private static void applyUIFont(Font font) {
        Enumeration<Object> keys = UIManager.getLookAndFeelDefaults().keys();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof Font) {
                Font derived = font.deriveFont(((Font) value).getStyle());
                UIManager.put(key, derived);
            }
        }

        for (Window window : Window.getWindows()) {
            SwingUtilities.updateComponentTreeUI(window);
        }
    }

    RegistrationSettingsItem() {
        this.mainWindow = null;
        registrationTopic = AxisInnovatorsBox.getMain().getRegistrationTopic();
    }

    public RegistrationSettingsItem(AxisInnovatorsBox main) {
        this.mainWindow = main;
        registrationTopic = main.getRegistrationTopic();
    }

    /**
     * 注册设置项
     *
     * @param tabbedPanesSettings 设置页面
     * @param title               标题
     * @param icon                显示图标（可为null）
     * @param tip                 描述
     * @param registeredName      注册名（必须是唯一的）
     */
    private void addSettings(JPanel tabbedPanesSettings,
                             String title,
                             Icon icon,
                             String tip,
                             String registeredName) {
        if (mainWindow != null) {
            if (!mainWindow.isWindow()) {
                registrationItem(tabbedPanesSettings, title, icon, tip, registeredName);
            } else {
                logger.warn("Wrong time to add tools");
            }
        } else {
            registrationItem(tabbedPanesSettings, title, icon, tip, registeredName);
        }
    }

    /**
     * 注册设置项
     *
     * @param tabbedPanesSettings 设置页面
     * @param title               标题
     * @param icon                显示图标（可为null）
     * @param tip                 描述
     * @param plugin              插件
     * @param registeredName      注册名（必须是唯一的）
     */
    public void addSettings(JPanel tabbedPanesSettings,
                            String title,
                            Icon icon,
                            String tip,
                            PluginDescriptor plugin,
                            String registeredName) {
        if (mainWindow != null) {
            if (!mainWindow.isWindow()) {
                registrationItem(tabbedPanesSettings, title, icon, tip, plugin.getRegistrationName()
                        + ":" +
                        registeredName);
            } else {
                logger.warn("Wrong time to add tools");
            }
        } else {
            registrationItem(tabbedPanesSettings, title, icon, tip, registeredName);
        }
    }

    /**
     * 通过 PluginDescriptor 查询整个插件装载的注册项
     *
     * @param plugin 插件描述符
     * @return List<RegistrationSettingsItem> 与指定插件相关的注册设置项列表
     */
    public static List<RegistrationSettingsItem> getRegistrationsByPlugin(PluginDescriptor plugin) {
        return registrationSettingsItemList.stream()
                .filter(item ->
                        item.getRegisteredNameList().stream()
                                .anyMatch(name ->
                                        name.startsWith(plugin.getRegistrationName() + ":"))
                )
                .collect(Collectors.toList());
    }

    private void registrationItem(JPanel tabbedPanesSettings, String title, Icon icon, String tip, String registeredName) {
        if (registeredNameList.contains(registeredName)) {
            throw new RegistrationError(registeredName + " duplicate registered names");
        }
        this.isEmpty = false;
        this.uuidList.add(UUID.randomUUID());
        this.tabbedPanesSettings.add(tabbedPanesSettings);
        this.titleList.add(title);
        this.iconList.add(icon);
        this.tipList.add(tip);
    }

    /**
     * 获取设置项
     *
     * @param id id
     * @return JPanel对象
     */
    public JPanel getSettings(UUID id) {
        for (int i = 0; i < uuidList.size(); i++) {
            if (uuidList.get(i).equals(id)) {
                return tabbedPanesSettings.get(i);
            }
        }
        return null;
    }

    /**
     * 通过注册名获取UUID
     *
     * @param registeredName 注册名
     * @return UUID
     */
    public UUID getUUID(String registeredName) {
        for (int i = 0; i < registeredNameList.size(); i++) {
            if (registeredNameList.get(i).equals(registeredName)) {
                return uuidList.get(i);
            }
        }
        return null;
    }

    /**
     * 注册设置项
     *
     * @param registrationSettingsItem 注册设置项
     */
    public void addRegistrationSettingsItem(RegistrationSettingsItem registrationSettingsItem) {
        if (registrationSettingsItem.isEmpty()) {
            logger.warn("Empty registration settings item");
            return;
        }
        registrationSettingsItemList.add(registrationSettingsItem);
    }

    /**
     * 注册设置项
     *
     * @param tabbedPane JTabbedPane
     */
    public void registration(JTabbedPane tabbedPane) {
        for (int i = 0; i < tabbedPanesSettings.size(); i++) {
            tabbedPane.addTab(titleList.get(i), iconList.get(i), tabbedPanesSettings.get(i), tipList.get(i));
        }
    }

    /**
     * 获取所有注册设置项
     *
     * @return List<RegistrationSettingsItem>
     */
    public static List<RegistrationSettingsItem> getRegistrationSettingsItemList() {
        return registrationSettingsItemList;
    }

    public List<UUID> getUUIDList() {
        return uuidList;
    }

    public List<String> getRegisteredNameList() {
        return registeredNameList;
    }

    public List<JPanel> getTabbedPanesSettings() {
        return tabbedPanesSettings;
    }

    public List<String> getTitleList() {
        return titleList;
    }

    public List<Icon> getIconList() {
        return iconList;
    }

    public List<String> getTipList() {
        return tipList;
    }

    public boolean isEmpty() {
        return isEmpty;
    }
}
