<%
  import java.net.URLEncoder;
  import javax.jcr.Node;
  import javax.jcr.AccessDeniedException ;
  import org.exoplatform.ecm.webui.utils.Utils;
  import org.exoplatform.web.application.Parameter ;
  import org.exoplatform.webui.core.UIRightClickPopupMenu;
  import org.exoplatform.ecm.webui.component.explorer.UIWorkingArea;
  import org.exoplatform.ecm.webui.component.explorer.sidebar.TreeNode ;
	import javax.jcr.PathNotFoundException;
  import java.util.List;
	import java.util.ArrayList;
  import org.exoplatform.ecm.utils.text.Text;
  import org.exoplatform.services.jcr.RepositoryService;  
  
%>
<%

  def idSelected = uicomponent.getEncodeCurrentPath();  
  _ctx.getRequestContext().getJavascriptManager().addOnLoadJavascript("eXo.ecm.ECMUtils.selectedPath('${idSelected}')");

  public void writeNodes(TreeNode rootTree) {
    UIRightClickPopupMenu contextMenu = uicomponent.getContextMenu();
    def uiCustomActionComponent = uicomponent.getWorkingArea().getCustomAction();
    String serverPath = uicomponent.getServerPath();
    String portalName = uicomponent.getPortalName();
    String restContextName = Utils.getRestContextName(portalName);
    RepositoryService rService = uicomponent.getApplicationComponent(RepositoryService.class) ;
    String repository = rService.getCurrentRepository().getConfiguration().getName() ;  
    String drive = uicomponent.getDriveName();
    int counter = 1 ;     
	  List childrenNodes=uicomponent.getRenderedChildren(rootTree);
    boolean isPaginated=uicomponent.isPaginated(rootTree);    
    
		def realChildrenTrees = new ArrayList<TreeNode>();
		for(tempNode in childrenNodes) {
			try {
				if (uicomponent.isAllowNodeTypesOnTree(tempNode.getNode())) {
					rootTree.getNode().getSession().getItem(tempNode.getNodePath());
					realChildrenTrees.add(tempNode);
				}
			} catch(PathNotFoundException pne) {
				continue;
			}			
		}
		int childrenSize = realChildrenTrees.size();        
    if(!uicomponent.isSystemWorkspace()) {
      def rcontext = _ctx.getRequestContext();
      int depth = rootTree.getNode().getDepth() + 1;
  		rcontext.getJavascriptManager().addOnLoadJavascript("eXo.ecm.ECMUtils.initClipboard('${drive}_treeclip_button','$depth','$childrenSize')");
    }

    for(treeNode in realChildrenTrees) {	    
			Node node = treeNode.getNode();			
    	node.refresh(true);
    	try {
    	  def primaryName = node.getPrimaryNodeType().getName();
    	} catch(Exception e) {
    	  continue;
    	}
	    String path = node.getPath() ;
	    String treeNodeName = uicomponent.getWorkingArea().getTitle(node);	    
	    def isPreferenceNode = uicomponent.isPreferenceNode(node) ;
	    def preferenceWS = node.getSession().getWorkspace().getName() ;
	    String mode = "ExpandTree";
	    String iconType = "Expand";
	    String actionLink  ;
	    String expandLink ;
	    if(treeNode.isExpanded()) { 
	      mode = "Collapse" ;
	      iconType = "Collapse";
	    }
	    if(isPreferenceNode) {
	      actionLink = uicomponent.event(mode, treeNode.getPath(), new Parameter("workspaceName", preferenceWS)) ;
	      expandLink = uicomponent.event("Expand", Utils.formatNodeName(treeNode.getPath()), new Parameter("workspaceName", preferenceWS)) ;
	    } else {
	      actionLink = uicomponent.event(mode, treeNode.getPath()) ;
	      expandLink = uicomponent.event("Expand", Utils.formatNodeName(treeNode.getPath())) ;
	    }
	    String strActs = "";
	    if(!uicomponent.isSystemWorkspace()) {
  	    strActs = "<div class=\"RightClickCustomItem\" style=\"display: none;\">" ;
        //Begin permlink
  	    def permLinkComponent =  uicomponent.getWorkingArea().getPermlink(node);
        if (permLinkComponent != null) {
         strActs +=  "<a class='MenuItem' style='display: block;' href=\"" + permLinkComponent.getPermlink(node) + "\" target='_new' onclick=\"return eXo.ecm.WCMUtils.hideContextMenu(this);\">";
         strActs +=  " <div class='MenuURLIcon " + permLinkComponent.getUIExtensionName() + "16x16Icon'>";
         strActs +=    _ctx.appRes("ECMContextMenu.event." + permLinkComponent.getUIExtensionName());
         strActs +=  " </div>";
         strActs +=  "</a>";
        }  
        //Begin for WebDav action
        if (!node.isNodeType(Utils.EXO_RESTORELOCATION) && !Utils.isTrashHomeNode(node)) {        
	  	    if (node.getPrimaryNodeType().getName().equals("nt:file")) {
	  	      String mimeType = "";
	  	      if (node.hasNode("jcr:content")) {
	  	        mimeType = node.getNode("jcr:content").getProperty("jcr:mimeType").getString();
	  	      }
	  	      // This escape "'" for js
	    		  String webDavPath = node.getPath().contains("%27") ? node.getPath().replaceAll("%27","%2527") : node.getPath();
	  		  	String link ="javascript:eXo.ecm.ECMUtils.generateWebDAVLink('"+ serverPath+"','"+ portalName +"','"+ restContextName +"','"+ repository +"','"+ preferenceWS+ "','" + webDavPath +"','"+mimeType+"')";				  					  					  	
	  	    	strActs += "<a class=\"MenuItem\" style='display: block;' onclick=\"return eXo.ecm.WCMUtils.hideContextMenu(this);\" href=\"" + link + "\">" ;	        
	  		  	strActs += "  <div class=\"ItemIcon WebDAV16x16Icon\">" + _ctx.appRes("UITreeExplorer.label.webDavView") + "</div>";
	  			  strActs += "</a>" ;				  	
	  		  } else {
	  		  	def nodeTarget = node;
					  if(uicomponent.isSymLink(node)) nodeTarget = Utils.getNodeSymLink(node);
						if (nodeTarget!= null) {	 
  	  		  	String link = serverPath + "/" + restContextName + "/private/jcr/" + repository + "/" + preferenceWS + Utils.formatNodeName(nodeTarget.getPath()); 
  	  	    	strActs += "<a class=\"MenuItem\" style='display: block; {behavior: url(#default#AnchorClick);}' onclick=\"return eXo.ecm.WCMUtils.hideContextMenu(this);\" href=\"" +link + "\" target='_new' folder=\"" + link +"\">" ;	        
  	  		  	strActs += "  <div class=\"ItemIcon WebDAV16x16Icon\">" + _ctx.appRes("UITreeExplorer.label.webDavView") + "</div>";
  	  			  strActs += "</a>" ;
						}
	  		  }
        }
  		  	  
  		  //End WebDAV Action					        
  		  List customActs = uicomponent.getCustomActions(node) ;				  
  	    Parameter[] params ;
  	    if(customActs.size() > 0) {				    
  			  for(act in customActs) {
  			    String actName = act.getProperty("exo:name").getValue().getString() ;
  			    params = [new Parameter("workspaceName", preferenceWS), new Parameter("actionName", Utils.formatNodeName(act.getName()))] ;
  			    strActs += "<a class=\"MenuItem\" style='display: block;' title=\"$actName\" onclick=\"return eXo.webui.UIRightClickPopupMenu.prepareObjectId(event, this);\" href=\"" + uiCustomActionComponent.event("Custom", Utils.formatNodeName(path), params) + "\">" ;
  		      strActs += "  <div class=\"ItemIcon " + Utils.getNodeTypeIcon(act, "16x16Icon") + "\">";
  		      if (actName.length() > 10) strActs += actName.substring(0, 10) + "...";
  		      else strActs += actName;
  			    strActs += "</div></a>" ;
  			  }				    
  	    }
  		
  			String clipboardLink = serverPath + "/" + restContextName + "/private/jcr/" + repository + "/" + preferenceWS + node.getPath();
  			int depthChild = node.getDepth();
        if (!node.isNodeType(Utils.EXO_RESTORELOCATION) && !Utils.isTrashHomeNode(node)) {  			
	  			strActs +=	"<a class='MenuItem' style='display: block;' id='${drive}_treeclip_button$depthChild$counter' path='$clipboardLink' onclick=\"eXo.ecm.ECMUtils.pushToClipboard(event,'$clipboardLink');\">" ;        
	  			strActs +=  "	<div class='MenuURLIcon GetURL16x16Icon'>" ;
	  			strActs +=	  _ctx.appRes("ECMContextMenu.event.GetURL");
	  			strActs +=  "	</div>" ;
	  			strActs += "</a>" ;
        }	  			
  			strActs += "</div>" ;	    
	    }
	    String lastNodeClass = "" ;
	    if (counter >= childrenSize && !isPaginated) {
	    	lastNodeClass = "LastNode " ;
	    }
	    def ctMenu = "" ;
	    def isLocked = false;
	    def lockedLabel = "";
      if (node.isLocked()) {
        isLocked = true;
        lockedLabel  = "("+_ctx.appRes("UIDocumentWorkspace.tooltip.LockedBy")+" "+node.getLock().getLockOwner()+")";
      }
	    def isSymLink = false;
	    def iconClassLink = "";
	    if(uicomponent.isSymLink(node)) {
	    	isSymLink = true;
	    	iconClassLink = "IconSymLink ";
	    }
	    
	    if(!uicomponent.isSymLink(node)) {		     
	      if(!uicomponent.hasChildNode(node)) iconType = "Empty";				
	    }
	    def hiddenStyle = "";
	    if (node.isNodeType("exo:hiddenable")) hiddenStyle = "color: #A0A0A0;";
	    if(!uicomponent.isSystemWorkspace()) ctMenu = contextMenu.getJSOnclickShowPopup(preferenceWS + ":" + Utils.formatNodeName(node.getPath()), uicomponent.getActionsList(node)) ;
	    println "<div  class=\"${lastNodeClass}Node\" >" ;
	    println "  <div class=\"${iconType}Icon\" id=\"" + uicomponent.encodeBase64(treeNode.getPath()) + "\" onclick=\"event.cancelBubble=true; if(eXo.ecm.ECMUtils.collapseExpand(this)) return; " + actionLink + "\">" ;
	    if (node.isLocked()) {
        println "<div class=\"IconLocked\"></div>";
	    }
	    println "    <div id=\"iconTreeExplorer" + treeNode.getNodePath4ID() + "\" onclick=\"event.cancelBubble=true;" + expandLink + "\" objectId=\"" + URLEncoder.encode(Utils.formatNodeName(treeNode.getPath()), "utf-8") + "\" workspacename=\"" + preferenceWS + "\" class=\"${iconClassLink}Icon16x16 default16x16Icon " + Utils.getNodeTypeIcon(node, "16x16Icon", iconType) + "\" " + ctMenu + ">" + strActs ;
	    println "      <div class='NodeLabel'>" ;
	    println "			   <a  onclick=\"event.cancelBubble=true;" + expandLink + "\" style='cursor: pointer;$hiddenStyle' title=\"$treeNodeName $lockedLabel\">$treeNodeName</a>" ;
	    println "      </div>" ; 
	    println "    </div>" ; 
	    println "  </div>" ; 
	    if(treeNode.getChildrenSize() > 0) {
	      println "<div class=\"NodeGroup\">" ;
	      writeNodes(treeNode) ;
	      if(uicomponent.isPaginated(treeNode)) {
			      println "<div class=\"Node PageIterator\">"	    	
		    		_ctx.renderUIComponent(uicomponent.getUIPageIterator(treeNode.getPath())); 				
		    		println "</div>" ;
		    }		    	
	      println "</div>" ;
	    }	    
	    println "</div>" ;	    	    	 			           	   
			counter ++ ;
		}			
  }  
  TreeNode treeNodeRoot = uicomponent.getRootTreeNode();
  treeNodeRoot.getNode().refresh(true);
  String contextMenuEvent = uicomponent.getRootActionList() ;
  def uiWorkingArea = uicomponent.getAncestorOfType(UIWorkingArea.class);
  def label = uicomponent.getLabel();
%>

<div class="JCRMoveAction" style="display: none;" 
		 request="<%=uiWorkingArea.getJCRMoveAction().event(UIWorkingArea.MOVE_NODE)%>" 
		 symlink="<%=uiWorkingArea.getCreateLinkAction().event(UIWorkingArea.CREATE_LINK)%>">
</div>
<div class="SideBarContent">
  <div class="BarContent">
  	<div class="BarContentL">
  		<div class="BarContentR">
  			<div class="BarContentM ClearFix">
			    <div class="Title" style="cursor: pointer;" title="$label" onclick="<%=uicomponent.event("Expand",treeNodeRoot.getPath())%>" $contextMenuEvent>
			      ${label}
			    </div>			  	
			  	
			  </div>
			</div>
		</div>
  </div>
  <div class="SideContent">
	  <div class="UITreeExplorer" id="UITreeExplorer">
		  <div style="white-space: nowrap; -moz-user-select: none;">
		    <div class="NodeGroup">
		      <%
		        //re-initialize action
		       writeNodes(treeNodeRoot);
    	     uicomponent.getWorkingArea().initialize();
		       if(uicomponent.isPaginated(treeNodeRoot)) {%>
		       			<div class="Node PageIterator">
		       				<% _ctx.renderUIComponent(uicomponent.getUIPageIterator(treeNodeRoot.getPath())); %>
		       			</div>       	
						<%}
					%>
		    </div>
		  </div>   	    
		</div>
  </div>
</div>