package com.k_int.it4me;

import java.util.Properties;
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.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.*;
import java.io.FileInputStream;

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

  /**static final String[] config_fields = { "name", 
                                          "publishURL",
                                          "sourceURL",
                                          "targetCollection", 
                                          "publisherIdentity", 
                                          "publisherCredentials"};
  **/
    
    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(DoncasterPublisher.class);

  private String targetCollection = "doncaster";
  private String sourceURL="/tmp/doncaster.xls";
 

  public void run() {
    log.debug("Starting run");

    try {
      POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(sourceURL));
      HSSFWorkbook wb = new HSSFWorkbook(fs);
      HSSFSheet sheet = wb.getSheetAt(2);

      boolean datarow = true;
      short rownum = 1;
      while ( datarow ) {
        HSSFRow row = sheet.getRow(rownum++);
        if ( row != null ) {
          ResourceDTO result = new ResourceDTO();

          HSSFCell id_cell = row.getCell((short)1);
          HSSFCell title_cell = row.getCell((short)2);
          HSSFCell contact_phone_1_cell = row.getCell((short)3);
          HSSFCell contact_phone_2_cell = row.getCell((short)4);
          HSSFCell contact_name_1_cell = row.getCell((short)5);
          HSSFCell contact_name_2_cell = row.getCell((short)6);
          HSSFCell contact_name_3_cell = row.getCell((short)7);
          HSSFCell web_cell = row.getCell((short)8);
          HSSFCell email_cell = row.getCell((short)9);
          HSSFCell email_2_cell = row.getCell((short)10);
          HSSFCell address_1_cell = row.getCell((short)11);
          HSSFCell address_2_cell = row.getCell((short)12);
          HSSFCell address_3_cell = row.getCell((short)13);
          HSSFCell address_4_cell = row.getCell((short)14);
          HSSFCell address_5_cell = row.getCell((short)15);
          HSSFCell desc_cell_1 = row.getCell((short)31);
          HSSFCell desc_cell_2 = row.getCell((short)32);
          HSSFCell desc_cell_3 = row.getCell((short)33);

          String id_string = null;
          String title_string = null;
          String web_string = null;
          String email_string = null;
          String description = null;
          String address_1 = null;
          String address_2 = null;
          String address_3 = null;
          String address_4 = null;
          String address_5 = null;
          String contact_name_1 = null;
          String contact_name_2 = null;
          String contact_name_3 = null;
          String contact_phone_1 = null;
          String contact_phone_2 = null;
          
          // double d = cell.getNumericCellValue();
          id_string = id_cell.getStringCellValue();
          title_string = title_cell.getStringCellValue();
          if ( web_cell != null ) web_string = web_cell.getStringCellValue(); 
          if ( email_cell != null ) email_string = email_cell.getStringCellValue();
          if ( desc_cell_1 != null ) description = desc_cell_1.getStringCellValue();
          if ( address_1_cell != null ) address_1 = address_1_cell.getStringCellValue();
          if ( address_2_cell != null ) address_2 = address_2_cell.getStringCellValue();
          if ( address_3_cell != null ) address_3 = address_3_cell.getStringCellValue();
          if ( address_4_cell != null ) address_4 = address_4_cell.getStringCellValue();
          if ( address_5_cell != null ) address_5 = address_5_cell.getStringCellValue();
          if ( contact_name_1_cell != null ) contact_name_1 = contact_name_1_cell.getStringCellValue();
          if ( contact_name_2_cell != null ) contact_name_2 = contact_name_2_cell.getStringCellValue();
          if ( contact_name_3_cell != null ) contact_name_3 = contact_name_3_cell.getStringCellValue();
          if ( contact_phone_1_cell != null ) contact_phone_1 = contact_phone_1_cell.getStringCellValue();
          if ( contact_phone_2_cell != null ) contact_phone_2 = contact_phone_2_cell.getStringCellValue();

          for ( int i=16; i<=30; i++ ) {
            HSSFCell cell = row.getCell((short)i);
            if ( cell != null ) {
              String subject_string = cell.getStringCellValue();
              System.err.println("subject: "+subject_string);
              if ( ( subject_string != null ) && ( subject_string.trim().length() > 0 ) ) {
                result.getSubjects().add(new SubjectDTO("Doncaster-UK", subject_string));
              }
            }
          }
          
          System.err.println(id_string+" "+title_string+" "+description);

          AvailabilityDTO availability = new AvailabilityDTO();
          // availability.setCost(fees_and_charges);
          // availability.setTimetextual(meeting_times);
          availability.getAddresses().add(new AddressDTO("Corresp", address_1, address_2, address_3, address_4,null,null,address_5,null));
          availability.getContacts().add(new ContactDTO(contact_name_1, contact_name_2, contact_name_3, contact_phone_1, contact_phone_2, null, email_string, web_string, null));
          result.getAvailability().add(availability);

           // Populate fields in the new resource
           result.setIdentifier(web_string);
           result.setTitle(title_string);
           result.setDescription(description);
           result.setPublisher("Doncaster Information Services");
           // 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.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);

          // Upload the new resource to the server
          controller.upload(result,
                            "Doncaster:"+id_string,
                            "Doncaster",  // Record Source
                            "Doncaster",                      // Publisher
                            "Doncaster-Credentials",          // Publisher Credentials
                            getPublishURL(),
                            getTargetCollection(),
                            "Doncaster-UK");
        }
        else {
          datarow = false;
          setStatus(UploadStatus.COMPLETED_OK);
        }
      }
    }
    catch ( com.k_int.ia.data_upload.DataPublishException dpe ) {
      dpe.printStackTrace();
    }
    catch ( java.io.FileNotFoundException fnfe ) {
      fnfe.printStackTrace();
    }
    catch ( java.io.IOException ioe ) {
      ioe.printStackTrace();
    }

    //setStatus(Messages.getString("HelpYourselfPublisher.26")); //$NON-NLS-1$
    if(this.getStatus()==UploadStatus.BUSY)
        this.setStatus(UploadStatus.FAILED);
    running = false;
    controller.notifyComplete(this);
    log.debug("Completed run");
    System.err.println("Finished Processing");
  }

  public String getSourceURL() {
    return sourceURL;
  }

 
  public void setSourceURL(String sourceURL) {
    this.sourceURL = sourceURL;    
  }

 
  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 getDataFromFile(Node n,String path) throws javax.xml.transform.TransformerException {
    String retval = null;
    Node temp_node = XPathAPI.selectSingleNode(n, path ,n);
    if ( temp_node != null ) {
      String data_string = temp_node.getNodeValue();
      retval = data_string;
    }
    return retval;
  }
  
}
