// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.daemon.impl.analysis;

import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.XmlRecursiveElementVisitor;
import com.intellij.psi.impl.source.xml.SchemaPrefix;
import com.intellij.psi.impl.source.xml.SchemaPrefixReference;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SequentialModalProgressTask;
import com.intellij.util.SequentialTask;
import com.intellij.xml.XmlBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Konstantin Bulenkov
 */
public class ConvertSchemaPrefixToDefaultIntention extends PsiElementBaseIntentionAction {

  public ConvertSchemaPrefixToDefaultIntention() {
    setText(XmlBundle.message("xml.intention.reset.to.default.namespace.name"));
  }

  @Override
  public void invoke(final @NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
    final XmlAttribute xmlns = getXmlnsDeclaration(element);
    if (xmlns == null) return;
    SchemaPrefixReference prefixRef = null;
    for (PsiReference ref : xmlns.getReferences()) {
      if (ref instanceof SchemaPrefixReference) {
        prefixRef = (SchemaPrefixReference)ref;
        break;
      }
    }
    if (prefixRef == null) return;

    final SchemaPrefix prefix = prefixRef.resolve();
    final String ns = prefixRef.getNamespacePrefix();
    final ArrayList<XmlTag> tags = new ArrayList<>();
    final ArrayList<XmlAttribute> attrs = new ArrayList<>();
    xmlns.getParent().accept(new XmlRecursiveElementVisitor() {
      @Override
      public void visitXmlTag(@NotNull XmlTag tag) {
        if (ns.equals(tag.getNamespacePrefix())) {
          tags.add(tag);
        }
        super.visitXmlTag(tag);
      }

      @Override
      public void visitXmlAttributeValue(@NotNull XmlAttributeValue value) {
        if (value.getValue().startsWith(ns + ":")) {
          for (PsiReference ref : value.getReferences()) {
            if (ref instanceof SchemaPrefixReference && ref.isReferenceTo(prefix)) {
              attrs.add((XmlAttribute)value.getParent());
            }
          }
        }
      }
    });

    if (!FileModificationService.getInstance().preparePsiElementsForWrite(xmlns.getContainingFile())) return;

    CommandProcessor.getInstance().executeCommand(project, () -> {
      convertTagsAndAttributes(ns, tags, attrs, project);
      ApplicationManager.getApplication().runWriteAction(() -> {
        xmlns.setName("xmlns");
      });
    }, XmlBundle.message("xml.intention.reset.to.default.namespace.command"), null);

    WriteCommandAction.writeCommandAction(project, xmlns.getContainingFile()).withName(
      XmlBundle.message("xml.intention.reset.to.default.namespace.command")).run(() -> xmlns.setName("xmlns"));
  }

  private static void convertTagsAndAttributes(String ns,
                                               final List<? extends XmlTag> tags,
                                               final List<? extends XmlAttribute> attrs,
                                               Project project) {
    final int localNameIndex = ns.length() + 1;
    final int totalCount = tags.size() + attrs.size();

    final SequentialModalProgressTask progressTask = new SequentialModalProgressTask(
      project, XmlBundle.message("xml.progress.changing.to.default.namespace"), true);
    progressTask.setTask(new SequentialTask() {
      int tagIndex = 0;
      int attrIndex = 0;

      @Override
      public boolean isDone() {
        return tagIndex + attrIndex >= totalCount;
      }

      @Override
      public boolean iteration() {
        progressTask.getIndicator().setFraction(((double)(tagIndex + attrIndex)) / totalCount);
        ApplicationManager.getApplication().runWriteAction(() -> {
          if (tagIndex < tags.size()) {
            XmlTag tag = tags.get(tagIndex++);
            final String s = tag.getName().substring(localNameIndex);
            if (!s.isEmpty()) {
              tag.setName(s);
            }
          }
          else if (attrIndex < attrs.size()) {
            XmlAttribute attr = attrs.get(attrIndex++);
            //noinspection ConstantConditions
            attr.setValue(attr.getValue().substring(localNameIndex));
          }
        });

        return isDone();
      }
    });
    ProgressManager.getInstance().run(progressTask);
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
    return getXmlnsDeclaration(element) != null;
  }

  @Override
  public @NotNull String getFamilyName() {
    return getText();
  }

  private static @Nullable XmlAttribute getXmlnsDeclaration(PsiElement element) {
    final PsiElement parent = element.getParent();
    if (!(parent instanceof XmlElement)) return null;
    for (PsiReference ref : parent.getReferences()) {
      if (ref instanceof SchemaPrefixReference) {
        final PsiElement elem = ref.resolve();
        if (elem != null) {
          final PsiElement attr = elem.getParent();
          if (attr instanceof XmlAttribute) {
            final PsiElement tag = attr.getParent();
            if (tag instanceof XmlTag && ((XmlTag)tag).getAttribute("xmlns") == null) {
              return (XmlAttribute)attr;
            }
          }
        }
      }
    }
    return null;
  }

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