package gitflow;

import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsListener;
import com.intellij.openapi.vcs.VcsRoot;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.util.messages.MessageBus;
import git4idea.GitVcs;
import gitflow.ui.GitflowWidget;
import org.jetbrains.annotations.NotNull;

/**
 * @author Opher Vishnia / opherv.com / opherv@gmail.com
 */
public class GitflowComponent implements ProjectComponent, VcsListener {
    Project myProject;
    GitflowWidget myGitflowWidget;
    MessageBus messageBus;

    public GitflowComponent(Project project) {
        myProject = project;
    }

    public void initComponent() {
        messageBus = myProject.getMessageBus();
        messageBus.connect().subscribe(ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED, this);
    }

    public void disposeComponent() {
        // TODO: insert component disposal logic here
    }

    @NotNull
    public String getComponentName() {
        return "GitflowComponent";
    }

    public void projectOpened() {

    }

    public void projectClosed() {

    }

    @Override
    public void directoryMappingChanged() {
        VcsRoot[] vcsRoots=ProjectLevelVcsManager.getInstance(myProject).getAllVcsRoots();

        //git repo present
        if (vcsRoots.length>0 && vcsRoots[0].getVcs() instanceof GitVcs){

            myGitflowWidget  = new GitflowWidget(myProject);
            StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject);
            if (statusBar != null) {
                statusBar.addWidget(myGitflowWidget, "after " + git4idea.ui.branch.GitBranchWidget.class.getName(), myProject);
            }
        }
        else{
            if (myGitflowWidget!=null){
                myGitflowWidget.deactivate();
            }
            myGitflowWidget = null;
        }
    }
}

@@ -1568,32 +1568,161 @@
 %0D%0A%0D%0A            
+//make sure to not reinitialize the widget if it's already present%0D%0A            if (myGitflowWidget ==  null) %7B%0D%0A                
 myGitflowWidget 
@@ -1720,17 +1720,16 @@
 owWidget
- 
  = new G
@@ -1746,32 +1746,36 @@
 et(myProject);%0D%0A
+    
             Stat
@@ -1854,24 +1854,28 @@
             
+    
 if (statusBa
@@ -1880,32 +1880,36 @@
 Bar != null) %7B%0D%0A
+    
                 
@@ -2013,32 +2013,51 @@
 ), myProject);%0D%0A
+                %7D%0D%0A
             %7D%0D%0A 

Fix #146 GitFlow re-initializes status bar menu when finishing hotfixes or checking out new branches