package com.huangzj.protoplugin.json;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextArea;
import com.intellij.util.ui.JBUI;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import org.jetbrains.annotations.Nullable;

/** 展示 JSON 文本并支持一键复制。 */
public final class ShowJsonResultDialog extends DialogWrapper {

    private final JBTextArea textArea;

    public ShowJsonResultDialog(Project project, String title, String json) {
        super(project);
        setTitle(title);
        textArea = new JBTextArea(json);
        textArea.setEditable(false);
        textArea.setCaretPosition(0);
        init();
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        JBScrollPane scroll = new JBScrollPane(textArea);
        scroll.setPreferredSize(new Dimension(560, 360));
        panel.add(scroll, BorderLayout.CENTER);
        JPanel south = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton copy = new JButton("复制到剪贴板");
        copy.addActionListener(
                e ->
                        Toolkit.getDefaultToolkit()
                                .getSystemClipboard()
                                .setContents(new StringSelection(textArea.getText()), null));
        south.add(copy);
        panel.add(south, BorderLayout.SOUTH);
        panel.setBorder(JBUI.Borders.empty(8));
        return panel;
    }

    @Override
    protected Action @Nullable [] createActions() {
        return new Action[] {getOKAction()};
    }
}
