package com.k_int.it4me;

//import java.io.FileOutputStream;
import java.sql.*;
import java.util.Date;
import java.util.Properties;
import javax.xml.parsers.*;
import com.k_int.ia.data_upload.dto.*;
import com.k_int.ia.data_upload.ConfigPair;
import com.k_int.ia.data_upload.ConfigTypes;
import com.k_int.ia.data_upload.DataPublishController;
import com.k_int.ia.data_upload.UploadStatus;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.*;
import org.apache.xpath.*;
import org.apache.xpath.objects.*;
import org.apache.xml.utils.*;
import org.apache.xpath.CachedXPathAPI;

public class GatesheadPublisher extends com.k_int.ia.data_upload.ThreadedDataPublisher 
{

    private CachedXPathAPI xpath = null;

    static ConfigPair[] config_fields; //= new ArrayList();
    
    static
    {
        config_fields = new ConfigPair[6];
        ConfigPair pair = new ConfigPair();
        pair.setFieldName("name");
        pair.setFieldType(ConfigTypes.TEXTFIELD);    
        config_fields[0]=pair;
       
        pair = new ConfigPair();
        pair.setFieldName("publishURL");
        pair.setFieldType(ConfigTypes.TEXTAREA);
        config_fields[1]=pair;
        
        pair = new ConfigPair();
        pair.setFieldName("sourceURL");
        pair.setFieldType(ConfigTypes.URL_SELECTION);
        config_fields[2]=pair;
        
        pair = new ConfigPair();
        pair.setFieldName("targetCollection");
        pair.setFieldType(ConfigTypes.TEXTFIELD);
        config_fields[3]=pair;
        
        pair = new ConfigPair();
        pair.setFieldName("publisherIdentity");
        pair.setFieldType(ConfigTypes.TEXTFIELD);
        config_fields[4]=pair;
        
        pair = new ConfigPair();
        pair.setFieldName("publisherCredentials");
        pair.setFieldType(ConfigTypes.PASSWORD);
        config_fields[5]=pair;
        
       
    }
  public static Log log = LogFactory.getLog(HelpYourselfPublisher.class);
  protected static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

  private String targetCollection = "gateshead";
  private String sourceURL="file:///home/liam/gateshead_library_oai_nice.xml";
  
  private transient Connection conn = null;
  private transient PreparedStatement get_org_details_ps = null;

  public GatesheadPublisher() {
    xpath = new CachedXPathAPI();
  }
 
  public void run() {
    log.debug("Starting run");

    try {
      dbf.setNamespaceAware(true);
      DocumentBuilder docBuilder = dbf.newDocumentBuilder();
      
      Document result_doc = docBuilder.parse(sourceURL);
     
      Element repository_node = result_doc.getDocumentElement();
      repository_node.setAttribute("xmlns:pndsdc","http://purl.org/mla/pnds/pndsdc/");

      NodeList nl = xpath.selectNodeList(repository_node,"//oai:record",repository_node);
      String default_authority = "gateshead";

      for ( int i=0; i<nl.getLength(); i++ ) {
        Node n = nl.item(i); 

        Node pndsdc_description = xpath.selectSingleNode(n,"./oai:metadata/pndsdc:description",repository_node);
        String id = getDataFromFile(n,"./oai:header/oai:identifier/text()");

        // Create a new resource object for each record from the xml file
        ResourceDTO result = new ResourceDTO();

        // Populate fields in the new resource
        result.setTitle(getDataFromFile(pndsdc_description,"./dc:title/text()"));
        int newi = i + 1;
        System.err.println("Processing node "+newi+"/"+nl.getLength()+" with title: "+getDataFromFile(pndsdc_description,"./dc:title/text()"));

        result.setDescription(getDataFromFile(pndsdc_description,"./dc:description/text()"));
        result.setPublisher(getDataFromFile(pndsdc_description,"./dc:publisher/text()"));
        result.setLanguage(getDataFromFile(pndsdc_description,"./dc:language/text()"));
        result.setType(getDataFromFile(pndsdc_description,"./dc:type/text()"));
        result.setFormat(getDataFromFile(pndsdc_description,"./dc:format/text()"));
        result.setAudience(getDataFromFile(pndsdc_description,"./dc:audience/text()"));
        result.setIdentifier(getDataFromFile(pndsdc_description,"./dc:identifier/text()"));
        result.setRights(getDataFromFile(pndsdc_description,"./dc:rights/text()"));
        result.setAlternate_title(getDataFromFile(pndsdc_description,"./dc:alternate_title/text()"));
        result.setMedium(getDataFromFile(pndsdc_description,"./dc:medium/text()"));
        result.setHasFormat(getDataFromFile(pndsdc_description,"./dc:hasFormat/text()"));
        result.setLast_modified((new Date()).getTime());
        result.setDate_issued(null);

	NodeList n2 = xpath.selectNodeList(pndsdc_description,"./dc:subject",pndsdc_description);
	for ( int j=0; j<n2.getLength(); j++ ) {
          Element sub_node = (Element)n2.item(j);
	  String subj_str = getDataFromFile(sub_node,"./text()");
	  if ((subj_str != null) && (subj_str.length() > 0)) {
	    String urlEnc = sub_node.getAttribute("encSchemeURI");
	    result.getSubjects().add(new SubjectDTO(urlEnc, subj_str));
	  }
	}

        n2 = xpath.selectNodeList(pndsdc_description,"./dcterms:spatial",pndsdc_description);
        for ( int j=0; j<n2.getLength(); j++ ) {
          Element sub_node = (Element)n2.item(j);
          String spat_str = getDataFromFile(sub_node,"./text()");
          if ((spat_str != null) && (spat_str.length() > 0)) {
            String urlEnc = sub_node.getAttribute("encSchemeURI");
            result.getSpatial_terms().add(new SpatialCoverageDTO(urlEnc, spat_str));
          }
        }

        n2 = xpath.selectNodeList(pndsdc_description,"./dc:creator",pndsdc_description);
        for ( int j=0; j<n2.getLength(); j++ ) {
          Element sub_node = (Element)n2.item(j);
          String creat_str = getDataFromFile(sub_node,"./text()");
          if ((creat_str != null) && (creat_str.length() > 0)) {
            result.getCreators().add(new CreatorDTO(creat_str));
          }
        }

        controller.upload(result,
                          id,
                          "Gateshead",  // Record Source
                          "Gateshead",                      // Publisher
                          "Gateshead-Credentials",          // Publisher Credentials
                          getPublishURL(),
                          getTargetCollection(),
                          default_authority);

      }
      setStatus(UploadStatus.COMPLETED_OK);
    }
    catch ( javax.xml.parsers.ParserConfigurationException pce ) {
        pce.printStackTrace();
    }
    catch ( java.io.UnsupportedEncodingException uee ) {
        uee.printStackTrace();
    }
    catch ( org.xml.sax.SAXException saxe ) {
        saxe.printStackTrace();
    }
    catch ( java.io.IOException ioe ) {
        ioe.printStackTrace();
    }
    catch ( javax.xml.transform.TransformerException tfe ) {
        tfe.printStackTrace();
    }
    catch ( com.k_int.ia.data_upload.DataPublishException dpe ) {
      dpe.printStackTrace();
    }
    if(this.getStatus()==UploadStatus.BUSY)
        this.setStatus(UploadStatus.FAILED);
    //setStatus(Messages.getString("HelpYourselfPublisher.26")); //$NON-NLS-1$
    running = false;
    controller.notifyComplete(this);
    log.debug("Completed run");
    System.err.println("Finished Processing");
  }
 
  public String getDataFromFile(Node n,String path) throws javax.xml.transform.TransformerException {
    String retval = null;
    Node temp_node = xpath.selectSingleNode(n, path ,n);
    if ( temp_node != null ) {
      String data_string = temp_node.getNodeValue();
      retval = data_string;
    }
    return retval;
  }
  
  public com.k_int.ia.codbif.xdevicegui.defs.XDLayoutHDO getLayout() {
      return new com.k_int.ia.codbif.xdevicegui.defs.XDLayoutHDO(
          "IT For Me Publisher",
          "com.k_int.it4me.messages",
          new com.k_int.ia.codbif.xdevicegui.defs.XDNameValuePairPanel(config_fields));
  }
  
  public String getTargetCollection() {
      return targetCollection;
    }
    public void setTargetCollection(String targetCollection) {
      this.targetCollection = targetCollection;
    }
    
    public String getSourceURL()
    {
        return sourceURL;
    }
    
    public void setSourceURL(String sourceURL)
    {
        this.sourceURL=sourceURL;
    }
  
}
