/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * published by the Free Software Foundation; either version 2.1 of
 * the license, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite
 * 330, Boston, MA  02111-1307, USA.
 * 
 */
package com.k_int.zthes;

import java.io.File;
import java.sql.SQLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.k_int.xrtree.DataNode;
import com.k_int.xrtree.DataTypes;
import com.k_int.xrtree.GenericXRDbManager;



/**
 * Title:		AssistedZThesWalker
 * @author: 	rob
 * @version:	$Id: v Exp $ 
 * @since			
 * Copyright:	1999-2007 Knowledge Integration Ltd
 * Company:		Knowledge Integration Ltd
 * Description:
 *
 *
 *
 * Created:		3 Jul 2008
 *
 *
 * History:
 *				$Log: v $
 *
 * 
 */

public class AssistedZThesWalker
{
  private File                    zthes_file;
  private Document                doc;
  private DocumentBuilder         doc_builder;
  private DocumentBuilderFactory  d_factory;
  //private HashMap                 data_nodes;
  //private HashMap                 categories;
  //private HashMap                 links;
  //private GenericXRDbManager      manager;
  //private boolean link_cats;
 
  private void setZthesFilename(String file_name) throws AnalysisException {
      zthes_file = new File(file_name);
      
      if(zthes_file.exists()==false || zthes_file.isDirectory())
          throw new AnalysisException("File "+file_name+" doesn't exist");
     
      try
      {
          buildDocumentFactory();
      }
      catch(Exception e)
      {
          throw new AnalysisException(e);
      }
  }
     
  private void buildDocumentFactory() throws Exception 
  {        
      d_factory   = DocumentBuilderFactory.newInstance();
      d_factory.setNamespaceAware(true);
      d_factory.setValidating(false);
      doc_builder = d_factory.newDocumentBuilder();                   
  }
  
  
  public void createLinks(GenericXRDbManager manager, String phase_year_view)throws AnalysisException
  {
    setZthesFilename(phase_year_view);
    try
    {
      extractLinks(manager);
    }
    catch(SQLException e)
    {
      e.printStackTrace();
      throw new AnalysisException(e);
    }
    
    
  }
  
  private void extractLinks(GenericXRDbManager manager)throws SQLException
  {
    try
    {
      doc               = doc_builder.parse(zthes_file);    
      NodeList terms = doc.getElementsByTagName("term");
      for (int i=0 ; i<terms.getLength();i++) 
      {
          Element term    = (Element) terms.item(i);  
          DataNode node   = buildDataNode(term);
          String id       = node.getId();
          NodeList relations = term.getElementsByTagName("relationType");
          
          for(int j=0;j<relations.getLength();j++) 
          {
  
              Element relationType = (Element) relations.item(j);       
              Element relation  = (Element) relationType.getParentNode();
              String rel_term_id =  ((Element) relation.getElementsByTagName("termId").item(0)).getTextContent();          
              manager.addLink(id, rel_term_id);
          }      
      }   
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }
  

  
  /*private void extractCategories(String id,Element term)
  {
    
    NodeList cat_nodes = term.getElementsByTagName("termCategory");
    List cat_ids = (List)categories.get(id);
    if(cat_ids==null)
    {
      cat_ids = new ArrayList();
      categories.put(id,cat_ids);
    }
    
    for(int i=0;i<cat_nodes.getLength();i++)
    {
      Element cat_elem = (Element)cat_nodes.item(i);
      String cat_id = cat_elem.getAttribute("identifier");
      if(cat_id!=null && cat_id.trim().length()>0)
      {
        if(cat_ids.contains(cat_id)==false)
          cat_ids.add(cat_id);
      }    
    }
  }*/
  
  
  /*private DataNode processVocabHeader(Element thes)
  {
      DataNode retval = new DataNode();
      if(link_cats)
        retval.setType(DataTypes.LINKED_ASSISTED_VOCAB);
      else
        retval.setType(DataTypes.REFERENCED_ASSISTED_VOCAB);
     
      String name = thes.getElementsByTagName("dc:title").item(0).getTextContent();
      String id = thes.getElementsByTagName("dc:identifier").item(0).getTextContent();
      String guid = extractGuid(thes)  ; 
      if(guid==null)
        guid=id;
       
      retval.setName(name);
      retval.setId(guid);
      retval.setSource(retval.getId());
      return retval;                
  }*/
  
  /*private String extractGuid(Element element) 
  {
      String retval=null;
      NodeList list = element.getElementsByTagName("thesNote");
      
      for(int i=0;i<list.getLength();i++)
      {
          Element note = (Element) list.item(i);
          String label = note.getAttribute("label");
          if(label!=null && label.equals("globallyUniqueId"))
          {
              retval = note.getTextContent();
              break;
          }
      }
           
      return retval;
  }*/
  
  private String extractSource(Element element)
  {
      String retval=null;
      NodeList list = element.getElementsByTagName("termNote");
      
      for(int i=0;i<list.getLength();i++)
      {
          Element note = (Element) list.item(i);
          String label = note.getAttribute("label");
          if(label.equals("source"))
          {
              retval = note.getTextContent();
              break;
          }
      } 
      if(retval==null || retval.trim().length()==0)
      {
        list = element.getElementsByTagName("termVocabulary");
        for(int j=0;j<list.getLength();j++)
        {
          Element vocab = (Element) list.item(j);
          retval=vocab.getTextContent();
        }
        
      }
      if(retval!=null)
        retval=retval.trim();
      return retval;
  }
  
  
  /*private void processData(DataNode vocab_root) throws SQLException 
  {       
      manager.addData(vocab_root);     
         
      Iterator i = data_nodes.keySet().iterator();
     
      while(i.hasNext())
      {
          DataNode node = (DataNode) data_nodes.get((String) i.next());  
          manager.addData(node);
          String id     = node.getId();
          List cats     = (List)categories.remove(id);
          List link_list = (List)links.remove(id);
          
          if(cats!=null && cats.size()>0)
          {
            Iterator j = cats.iterator();
            while(j.hasNext())
            {
              String cat = (String) j.next();
             
              manager.addCategory(id, cat.trim());
              
            }
          }
          
          if(link_list!=null && link_list.size()>0)
          {
            Iterator j = link_list.iterator();
            while(j.hasNext())
            {
              String link = (String) j.next();
            
              manager.addLink(id, link.trim());
            }
          }
      }
  }*/
  
  
  
  
 private DataNode buildDataNode(Element term)
 {
      String name = ((Element) term.getElementsByTagName("termName").item(0)).getTextContent().trim();
      String id  =  ((Element) term.getElementsByTagName("termId").item(0)).getTextContent().trim();
      //System.out.println("Building data node for: "+name+": "+id);
      NodeList types = term.getElementsByTagName("termType");
      int type = 0;
      if(types.getLength()>0)
      {   
          String term_type=  ((Element) term.getElementsByTagName("termType").item(0)).getTextContent();
          if(term_type!=null && term_type.trim().equals("")==false)
          {
              if(term_type.equals("PT"))
                 type=DataTypes.PT; 
              else if(term_type.equals("NL"))
                  type = DataTypes.NL;
              else if (term_type.equals("ND"))
                  type=DataTypes.NPT;          
          }
      }     
      
      DataNode result = new DataNode();
      result.setSource(extractSource(term));
      result.setType(type);
      result.setName(name);
      result.setId(id);
      return result;
  }

}
