package com.huangzj.protoplugin.json;

import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
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.PsiIdentifier;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

/** 光标在类名标识符上时，确认后生成默认 JSON。 */
public final class ClassToJsonIntention extends PsiElementBaseIntentionAction {

    @Override
    public @NotNull String getFamilyName() {
        return "Idea-Plugin JSON";
    }

    @Override
    public @NotNull String getText() {
        return "是否生成 JSON（默认值）…";
    }

    @Override
    public boolean isAvailable(
            @NotNull Project project, Editor editor, @NotNull PsiElement element) {
        if (!(element instanceof PsiIdentifier)) {
            return false;
        }
        PsiElement parent = element.getParent();
        if (!(parent instanceof PsiClass)) {
            return false;
        }
        PsiClass cls = (PsiClass) parent;
        PsiIdentifier id = cls.getNameIdentifier();
        return id != null && id.equals(element);
    }

    @Override
    public void invoke(
            @NotNull Project project, Editor editor, @NotNull PsiElement element)
            throws IncorrectOperationException {
        PsiElement parent = element.getParent();
        if (!(parent instanceof PsiClass)) {
            return;
        }
        PsiClass cls = (PsiClass) parent;
        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();
    }

    @Override
    public boolean startInWriteAction() {
        return false;
    }
}
