/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Chris Magnussen and Elior Boukhobza
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *
 */

package com.mallowigi.icons;

import com.intellij.icons.AllIcons;
import com.intellij.ide.IconProvider;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.roots.ui.configuration.SourceRootPresentation;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.jrt.JrtFileSystem;
import com.intellij.openapi.vfs.newvfs.ArchiveFileSystem;
import com.intellij.psi.JavaDirectoryService;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.ElementBase;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.PlatformIcons;
import com.mallowigi.icons.associations.PsiElementAssociation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * Provider for file icons
 */
public final class FileIconProvider extends IconProvider {

  private final Associations associations = Associations.AssociationsFactory.create();

  @Nullable
  @Override
  public Icon getIcon(@NotNull PsiElement psiElement, int i) {
    Icon icon = null;

    // Only replace icons on elements representing a file
    // Prevents file icons from being assigned to classes, methods, fields, etc.
    if (psiElement instanceof PsiFile) {
      VirtualFile virtualFile = PsiUtilCore.getVirtualFile(psiElement);
      if (virtualFile != null) {
        FileInfo file = new VirtualFileInfo(psiElement, virtualFile);
        icon = getIconForAssociation(file, associations.findAssociationForFile(file));
      }
    } else if (psiElement instanceof PsiDirectory) {
      icon = getDirectoryIcon((PsiDirectory) psiElement);
    }

    return icon;
  }

  /**
   * Get the relevant icon for association
   *
   * @param file        a file
   * @param association the found association
   * @return the replaced icon, or null if not found
   */
  private Icon getIconForAssociation(FileInfo file, Association association) {
    boolean isInputInvalid = association == null || association.getIcon() == null;
    return isInputInvalid ? null : loadIcon(file, association);
  }

  /**
   * Return correct instance of directory icon (taken straight from the source code)
   *
   * @param directory the directory
   * @return the directory icon
   */
  private Icon getDirectoryIcon(PsiDirectory directory) {
    VirtualFile vFile = directory.getVirtualFile();
    Project project = directory.getProject();

    SourceFolder sourceFolder;
    Icon symbolIcon = null;

    boolean hasJFS;
    try {
      Class.forName("com.intellij.openapi.vfs.jrt.JrtFileSystem");
      hasJFS = true;
    } catch (ClassNotFoundException e) {
      hasJFS = false;
    }

    boolean hasJDS;
    try {
      Class.forName("com.intellij.psi.JavaDirectoryService");
      hasJDS = true;
    } catch (ClassNotFoundException e) {
      hasJDS = false;
    }

    if (vFile.getParent() == null && vFile.getFileSystem() instanceof ArchiveFileSystem) {
      symbolIcon = PlatformIcons.JAR_ICON;
    } else if (ProjectRootsUtil.isModuleContentRoot(vFile, project)) {
      Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(vFile);
      symbolIcon = module != null ? ModuleType.get(module).getIcon() : PlatformIcons.CONTENT_ROOT_ICON_CLOSED;
    } else if ((sourceFolder = ProjectRootsUtil.getModuleSourceRoot(vFile, project)) != null) {
      symbolIcon = SourceRootPresentation.getSourceRootIcon(sourceFolder);
    } else if (hasJFS && JrtFileSystem.isModuleRoot(vFile)) {
      symbolIcon = AllIcons.Nodes.JavaModuleRoot;
    } else if (hasJDS && JavaDirectoryService.getInstance().getPackage(directory) != null) {
      symbolIcon = PlatformIcons.PACKAGE_ICON;
    } else if (!Registry.is("ide.hide.excluded.files") && ProjectRootManager.getInstance(project).getFileIndex().isExcluded(vFile)) {
      symbolIcon = AllIcons.Modules.ExcludeRoot;
    }

    if (symbolIcon != null) {
      return ElementBase.createLayeredIcon(directory, symbolIcon, 0);
    }
    return null;
  }

  /**
   * Find the icon specified by the association and load it
   *
   * @param file        the file
   * @param association the association found
   * @return the icon if found, null otherwise
   */
  private Icon loadIcon(FileInfo file, Association association) {
    Icon icon = null;

    try {
      if (association instanceof PsiElementAssociation) {
        icon = ((PsiElementAssociation) association).getIconForFile(file);
      } else {
        icon = IconLoader.getIcon(association.getIcon());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return icon;
  }
}

@@ -1421,16 +1421,63 @@
 leType;%0A
+import com.intellij.openapi.project.DumbAware;%0A
 import c
@@ -2482,16 +2482,37 @@
 rovider 
+implements DumbAware 
 %7B%0A%0A  pri

make it DumbAware