/*
 * Version 1.1
 * CeCILL Copyright (c) 2006-2007, AtolCD, ADULLACT-projet
 * Initiated by AtolCD S.A. & ADULLACT-projet S.A.
 * Developped by AtolCD
 * 
 * contact@atolcd.com
 * contact@adullact-projet.coop
 * 
 * Ce logiciel est un programme informatique servant à faire circuler des 
 * documents au travers d'un circuit de validation, où chaque acteur vise 
 * le dossier, jusqu'à l'étape finale de signature.
 * 
 * Ce logiciel est régi par la licence CeCILL soumise au droit français et
 * respectant les principes de diffusion des logiciels libres. Vous pouvez
 * utiliser, modifier et/ou redistribuer ce programme sous les conditions
 * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA 
 * sur le site "http://www.cecill.info".
 * 
 * En contrepartie de l'accessibilité au code source et des droits de copie,
 * de modification et de redistribution accordés par cette licence, il n'est
 * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,
 * seule une responsabilité restreinte pèse sur l'auteur du programme,  le
 * titulaire des droits patrimoniaux et les concédants successifs.
 * 
 * A cet égard  l'attention de l'utilisateur est attirée sur les risques
 * associés au chargement,  à l'utilisation,  à la modification et/ou au
 * développement et à la reproduction du logiciel par l'utilisateur étant 
 * donné sa spécificité de logiciel libre, qui peut le rendre complexe à 
 * manipuler et qui le réserve donc à des développeurs et des professionnels
 * avertis possédant  des  connaissances  informatiques approfondies.  Les
 * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du
 * logiciel à leurs besoins dans des conditions permettant d'assurer la
 * sécurité de leurs systèmes et ou de leurs données et, plus généralement, 
 * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. 
 * 
 * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez 
 * pris connaissance de la licence CeCILL, et que vous en avez accepté les
 * termes.
 *  
 */

package com.atolcd.parapheur.web.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.event.ActionEvent;

import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.web.bean.BrowseBean;
import org.alfresco.web.bean.NavigationBean;
import org.alfresco.web.bean.repository.MapNode;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.ui.common.component.UIActionLink;

import com.atolcd.parapheur.repo.ParapheurService;


public class SpaceDossierDetailsBean
{
    
    /** The NavigationBean bean reference */
    protected NavigationBean navigator;
    
    /** The browse bean */
    protected BrowseBean browseBean;
    
    /** NodeService bean reference */
    protected NodeService nodeService;
    
    protected ParapheurService parapheurService;
    
    
    /**
     * Sets the BrowseBean instance to use to retrieve the current document
     * 
     * @param browseBean BrowseBean instance
     */
    public void setBrowseBean(BrowseBean browseBean)
    {
       this.browseBean = browseBean;
    }
    
    /**
     * @param navigator The NavigationBean to set.
     */
    public void setNavigator(NavigationBean navigator)
    {
       this.navigator = navigator;
    }
    
    /**
     * @param nodeService        The NodeService to set.
     */
    public void setNodeService(NodeService nodeService)
    {
       this.nodeService = nodeService;
    }
    
    /**
    * @param parapheurService The parapheurService to set.
    */
   public void setParapheurService(ParapheurService parapheurService)
   {
      this.parapheurService = parapheurService;
   }

   /**
     * Returns the id of the current space
     * 
     * @return The id
     */
    public String getId()
    {
       return this.browseBean.getActionSpace().getId();
    }
    
    /**
     * Returns the name of the current space
     * 
     * @return Name of the current space
     */
    public String getName()
    {
        return this.browseBean.getActionSpace().getName();
    }
    
    /**
     * Returns the Space this bean is currently representing
     * 
     * @return The Space Node
     */
    public Node getSpace()
    {
        return this.browseBean.getActionSpace();
    }
    
    
    /**
     * Navigates to next item in the list of Spaces
     */
    public void nextItem(ActionEvent event)
    {
       UIActionLink link = (UIActionLink)event.getComponent();
       Map<String, String> params = link.getParameterMap();
       String id = params.get("id");
       if (id != null && id.length() != 0)
       {
          List<Node> dossiers = this.getDossiers();
          if (dossiers.size() > 1)
          {
             for (int i=0; i<dossiers.size(); i++)
             {
                if (id.equals(dossiers.get(i).getId()) == true)
                {
                   Node next;
                   // found our item - navigate to next
                   if (i != dossiers.size() - 1) next = dossiers.get(i + 1);
                   else next = dossiers.get(0);
                   
                   this.navigator.setCurrentNodeId(next.getId());
                   // prepare for showing details for this node
                   this.browseBean.setupSpaceAction(next.getId(), false);
                }
             }
          }
       }
    }
    
    
    /**
     * Navigates to the previous item in the list Spaces
     */
    public void previousItem(ActionEvent event)
    {
       UIActionLink link = (UIActionLink)event.getComponent();
       Map<String, String> params = link.getParameterMap();
       String id = params.get("id");
       if (id != null && id.length() != 0)
       {
          List<Node> dossiers = this.getDossiers();
          if (dossiers.size() > 1)
          {
             // see above
             for (int i=0; i<dossiers.size(); i++)
             {
                if (id.equals(dossiers.get(i).getId()) == true)
                {
                   Node previous;
                   // found our item - navigate to previous
                   if (i != 0) previous = dossiers.get(i - 1);
                   else previous = dossiers.get(dossiers.size() - 1);
                   
                   this.navigator.setCurrentNodeId(previous.getId());
                   // show details for this node
                   this.browseBean.setupSpaceAction(previous.getId(), false);
                }
             }
          }
       }
    }
    
    private List<Node> getDossiers()
    {
       List<Node> dossiers = null;
       
       // get the current space from NavigationBean
       String parentNodeId = this.navigator.getCurrentNodeId();
       
       NodeRef parentRef;
       if (parentNodeId == null)
       {
          // no specific parent node specified - use the root node
          parentRef = this.nodeService.getRootNode(Repository.getStoreRef());
       }
       else
       {
          // build a NodeRef for the specified Id and our store
          parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId);
       }
       
       if (this.parapheurService.isDossier(parentRef))
       {
          List<ChildAssociationRef> parentRefs = this.nodeService.getParentAssocs(parentRef,
                ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
          
          List<ChildAssociationRef> childRefs = this.nodeService.getChildAssocs(parentRefs.get(0).getParentRef(),
                ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
          dossiers = new ArrayList<Node>(childRefs.size());
          
          NodeRef nodeRef = null;
          MapNode node = null;
          
          for (ChildAssociationRef ref: childRefs)
          {
             // create our Node representation from the NodeRef
             nodeRef = ref.getChildRef();
             
             if (this.nodeService.exists(nodeRef) && this.parapheurService.isDossier(nodeRef))
             {
                node = new MapNode(nodeRef, this.nodeService, true);
                dossiers.add(node);
             }
          }
       }
       
       return dossiers;
    }
    
}
