package com.huangzj.protoplugin.json;

import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.openapi.editor.Editor;
import org.jetbrains.annotations.NotNull;

/** 编辑器右键：对光标所在类生成默认 JSON（与意图行为一致）。 */
public final class GenerateClassJsonEditorAction extends AnAction {

    @Override
    public void update(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        boolean javaFile = file instanceof PsiJavaFile && editor != null;
        PsiClass cls = null;
        if (javaFile) {
            int off = editor.getCaretModel().getOffset();
            PsiElement at = file.findElementAt(off);
            cls = PsiTreeUtil.getParentOfType(at, PsiClass.class);
        }
        boolean ok = project != null && cls != null;
        String place = e.getPlace();
        if (ActionPlaces.isPopupPlace(place)) {
            e.getPresentation().setEnabledAndVisible(ok);
        } else {
            e.getPresentation().setVisible(true);
            e.getPresentation().setEnabled(ok);
        }
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (project == null || !(file instanceof PsiJavaFile) || editor == null) {
            return;
        }
        int off = editor.getCaretModel().getOffset();
        PsiElement at = file.findElementAt(off);
        PsiClass cls = PsiTreeUtil.getParentOfType(at, PsiClass.class);
        if (cls == null) {
            return;
        }
        int r =
                Messages.showYesNoDialog(
                        project,
                        "是否根据当前类「" + cls.getName() + "」生成带默认值的 JSON？",
                        "生成 JSON",
                        Messages.getQuestionIcon());
        if (r != Messages.YES) {
            return;
        }
        String json = JavaClassToJsonBuilder.buildPrettyJson(cls);
        new ShowJsonResultDialog(project, "JSON — " + cls.getName(), json).show();
    }
}
