package com.karateca.ddescriber.model;

import com.intellij.find.FindResult;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.*;
import com.karateca.ddescriber.ActionUtil;
import com.karateca.ddescriber.Hierarchy;
import com.karateca.ddescriber.JasmineFinder;

import javax.swing.tree.MutableTreeNode;
import java.util.Enumeration;
import java.util.List;

/**
 * @author Andres Dominguez.
 *         TODO: remove when file is deleted.
 */
public class JasmineFile {
  private final Project project;
  private final VirtualFile virtualFile;
  private TreeNode treeNode;

  public JasmineFile(Project project, VirtualFile virtualFile) {
    this.project = project;
    this.virtualFile = virtualFile;

    // Listen for changes in the file to update the tree node.
    // TODO: listen for delete.
    VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() {
      @Override
      public void contentsChanged(VirtualFileEvent event) {
        if (treeNode != null) {
          updateTreeNode();
        }
      }
    });
  }

  private void updateTreeNode() {
    treeNode.removeAllChildren();
    TreeNode newRoot = createRootNode();
    treeNode.setUserObject(newRoot.getUserObject());
    Enumeration children = newRoot.children();
    while (children.hasMoreElements()) {
      treeNode.add((MutableTreeNode) children.nextElement());
    }
  }

  public TreeNode buildTreeNode() {
    treeNode = createRootNode();
    return treeNode;
  }

  private TreeNode createRootNode() {
    Document document = ActionUtil.getDocument(virtualFile);
    JasmineFinder jasmineFinder = new JasmineFinder(project, document);
    jasmineFinder.findAll();
    List<FindResult> findResults = jasmineFinder.getFindResults();
    Hierarchy hierarchy = new Hierarchy(document, findResults);
    return ActionUtil.populateTree(hierarchy.getAllUnitTests());
  }
}

@@ -1153,42 +1153,8 @@
 ) %7B%0A
-    treeNode.removeAllChildren();%0A
     
@@ -1185,24 +1185,92 @@
 eRootNode();
+%0A%0A    // Replace contents of node.%0A    treeNode.removeAllChildren();
 %0A    treeNod
@@ -1306,24 +1306,50 @@
 erObject());
+%0A%0A    // Replace children.
 %0A    Enumera
@@ -1692,16 +1692,17 @@
 lFile);%0A
+%0A
     Jasm
@@ -1857,24 +1857,25 @@
 dResults();%0A
+%0A
     Hierarch
@@ -1926,16 +1926,17 @@
 sults);%0A
+%0A
     retu

add speces and comments