package net.stevechaloner.idea.closeallx;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataConstants;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;

/**
 * Editor popup menu-suitable action that closes all files of the same type
 * as that open in the editor of the clicked tab.
 */
public class CloseAllXEditorAction extends AnAction
{
    // javadoc inherited
    public void actionPerformed(AnActionEvent e)
    {
        String extension = getExtension(e.getDataContext());
        if (extension != null)
        {
            Project project = ProjectManager.getInstance().getDefaultProject();
            CloseAllXComponent closeAllXComponent = project.getComponent(CloseAllXComponent.class);
            closeAllXComponent.closeEditorsOfType(extension,
                                                  e.getDataContext());
        }
    }

    /**
     * Gets the extension of the selected file.
     *
     * @param dataContext the data context of this operation
     * @return the extension, or null if no file is selected
     */
    private String getExtension(DataContext dataContext)
    {
        VirtualFile file = (VirtualFile)dataContext.getData(DataConstants.VIRTUAL_FILE);
        return file == null ? null : file.getExtension();
    }
}
