/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ellectra.gui.managebeans;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;
import org.apache.myfaces.custom.fileupload.UploadedFile;
//import org.ellectra.HttpServletUtil.HttpServletUtil;
import org.ellectra.fileutils.FileUtil;
import org.ellectra.gui.utils.JSFUtils;
import org.ellectra.wscdm.CdocumentService;
import org.ellectra.wscdm.Response.Query;

/**
 *
 * @author tdi
 */
public class calldetailsdocuments {
    @WebServiceRef(wsdlLocation = "http://localhost:18181/cdocumentService/cdocumentPort?wsdl")
    private CdocumentService service;
    private UIData odocs = null;
	
    private ArrayList<cdocumentlist> adocs= new ArrayList();
    
    private String desc;
    private String language;
    private String filename;
    private UploadedFile uploadedFile;
    
    //String szPath = "/applications/AppServers/jboss-4.0.3SP1/server/default/deploy/";
//    private String szPath ="c:\\upload\\";
    private String szPath = "/Users/gpa/upload/";
    //private String szPath = "/applications/AppServers/jboss-4.0.3SP1/server/default/deploy/";
    String dUserloginname;
    String dUserloginsignature;
    String dUserloginOrganization;
    String dUserloginrole;
    String dUserlogintenderid;
    String dUserloginid;
    int mytenderid;
    // Actions ------------------------------------------------------------------------------------

    public calldetailsdocuments()
    {
        super();
        pathSettings dset=new pathSettings();
        szPath=dset.GetUploadDirectory();
        
    }
    public void GetSessionVariables()
    {
        
        dUserloginname=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINUSER");
        dUserloginsignature=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINSIGNATURE");
        dUserloginOrganization=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINORGANIZATION");
        dUserloginrole=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINROLE");
        dUserlogintenderid=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "TENDERID");
        dUserloginid=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINUSERID");
        String dtemp=(String)JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID");
        mytenderid=Integer.valueOf(dtemp).intValue();
    }
    
   public void addToListp(ActionEvent event) {
		cdocumentlist pp = new cdocumentlist();
		//pp.setName(a_au1);
                pp.setFilename(filename);
                pp.setFilenamepathdoc(szPath+filename);
                pp.setLanguage(language);
                pp.setTitle(desc);
                pp.setType("pdf");
                Calendar cal = Calendar.getInstance(TimeZone.getDefault()); 
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; 
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getDefault()); 
String currentTime = sdf.format(cal.getTime()); 
                pp.setCreationdate(currentTime);
		adocs.add(pp);
		
                try { // Call Web Service Operation
                    org.ellectra.wscdm.CdocumentPortType port = service.getCdocumentPort();

                    org.ellectra.wscdm.Request request = new org.ellectra.wscdm.Request();
                    request.setAction("UPLOADDOCUMENT");
                    request.setCftid(mytenderid);
                    request.setDesc(desc);
                    request.setFilename(filename);
                    request.setLanguage(language);
                    String sdoctype=filename.substring(filename.length()-3, filename.length());
                    request.setMime(sdoctype);
                    request.setType(sdoctype);
                    request.setStatus("UPLOAD");
                    XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
                    request.setTimestamp(calendar);
                    request.setUserid(Integer.valueOf(dUserloginid).intValue());
                    request.setSignature(dUserloginsignature);
                    request.setDocid(1);
                    org.ellectra.wscdm.Response result = port.cdocumentOperation(request);
                    
                } catch (Exception ex) {
                    // TODO handle custom exceptions here
                }
	
		
	}
   
   public void publisht()
   {
       for (int i=0;i<adocs.size();i++)
       {
           cdocumentlist ps = adocs.get(i);
          try { // Call Web Service Operation
                    org.ellectra.wscdm.CdocumentPortType port = service.getCdocumentPort();

                    org.ellectra.wscdm.Request request = new org.ellectra.wscdm.Request();
                    request.setAction("PUBLISHDOC");
                  //  System.err.print("To tender" + mytenderid);
                    request.setCftid(mytenderid);
                    request.setDesc("d");
                    request.setFilename("d");
                    request.setLanguage("d");
                    
                    request.setMime("d");
                    request.setType("d");
                    request.setStatus("PUBLISHED");
                    XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
                    request.setTimestamp(calendar);
                    request.setUserid(Integer.valueOf(dUserloginid).intValue());
                    request.setSignature(dUserloginsignature);
                    request.setDocid(ps.getIcid());
                    org.ellectra.wscdm.Response result = port.cdocumentOperation(request);
                    
                } catch (Exception ex) {
                    // TODO handle custom exceptions here
                } 
       }
   }
   public void PopulateList()
   {
       adocs.clear();
       GetSessionVariables();
       try { // Call Web Service Operation
           org.ellectra.wscdm.CdocumentPortType port = service.getCdocumentPort();

           org.ellectra.wscdm.Request request = new org.ellectra.wscdm.Request();
              request.setAction("QUERY");
                    request.setCftid(mytenderid);
                    request.setDesc("desc");
                    request.setFilename("filename");
                    request.setLanguage("language");
                    // System.err.print("To tender" + mytenderid);
                    request.setMime("11");
                    request.setType("22");
                    request.setStatus("22");
                    XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
                    request.setTimestamp(calendar);
                    request.setUserid(Integer.valueOf(dUserloginid).intValue());
                    request.setSignature(dUserloginsignature);
                    request.setDocid(1);
                    //System.err.print("Before results");
           org.ellectra.wscdm.Response result = port.cdocumentOperation(request);
           //System.err.print("After results");
           for (int i = 0;i<result.getQuery().size();i++)
           {
               
             //  System.err.print("---- Inside found "+i);
               cdocumentlist e = new cdocumentlist();
               org.ellectra.wscdm.Response.Query ditem= result.getQuery().get(i);
               //System.err.print("before if ");
               if(ditem.getDesc().equalsIgnoreCase("NANULL"))
               {}else
               {
               //System.err.print("Inside 1");
               GregorianCalendar g = ditem.getTimestamp().toGregorianCalendar();
               String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; 
               java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
                sdf.setTimeZone(TimeZone.getDefault()); 
                String currentTime = sdf.format(g.getTime()); 
                //System.err.print("Inside 2");
                GregorianCalendar g2 = ditem.getPublishdate().toGregorianCalendar();
               String DATE_FORMAT2 = "yyyy-MM-dd HH:mm:ss"; 
               java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat(DATE_FORMAT2);
                sdf2.setTimeZone(TimeZone.getDefault()); 
                String currentTime2 = sdf2.format(g2.getTime()); 
                //System.err.print("Inside 3");
               e.setCreationdate(currentTime);
               //System.err.print("Inside 4");
               e.setPublicationdate(currentTime2);
               //System.err.print("Inside 5");
               e.setFilename(ditem.getFilename());
               e.setFilenamepathdoc(szPath+ditem.getFilename());
               //System.err.print("Inside 6");
               e.setLanguage(ditem.getLanguage());
               //System.err.print("Inside 7");
               e.setIcid(ditem.getDocid());
               //System.err.print("Inside 8");
               e.setTitle(ditem.getDesc());
               //System.err.print("Inside 9");
               e.setMime(ditem.getMime());
               //System.err.print("Inside 10");
               e.setType(ditem.getType());
               adocs.add(e);
               //System.err.print("Inside OK");
               }
               
           }
           //System.out.println("Result = "+result);
       } catch (Exception ex) {
           // TODO handle custom exceptions here
           System.err.print("Inside ERRORS"+ex.getLocalizedMessage()+" mes"+ex.getMessage());
       }

   }
   public void addToListdocs() {
       //System.err.print("Adding on list");
		cdocumentlist pp = new cdocumentlist();
		//pp.setName(a_au1);
                pp.setFilename(filename);
                pp.setLanguage(language);
                
                pp.setTitle(desc);
                pp.setType("pdf");
                Calendar cal = Calendar.getInstance(TimeZone.getDefault()); 
String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; 
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getDefault()); 
String currentTime = sdf.format(cal.getTime()); 
                pp.setCreationdate(currentTime);
                
		adocs.add(pp);
       //System.err.print("Adding on list OK");         
                try { // Call Web Service Operation
         //           System.err.print("Adding on DB ");         
                    org.ellectra.wscdm.CdocumentPortType port = service.getCdocumentPort();

                    org.ellectra.wscdm.Request request = new org.ellectra.wscdm.Request();
                    request.setAction("UPLOADDOCUMENT");
                    request.setCftid(mytenderid);
                    request.setDesc(desc);
                    request.setFilename(filename);
                    request.setLanguage(language);
                    String sdoctype=filename.substring(filename.length()-3, filename.length());
                    request.setMime(sdoctype);
                    request.setType(sdoctype);
                    request.setStatus("UPLOAD");
                    XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
                    request.setTimestamp(calendar);
                    request.setUserid(Integer.valueOf(dUserloginid).intValue());
                    request.setSignature(dUserloginsignature);
                    request.setDocid(1);
                    org.ellectra.wscdm.Response result = port.cdocumentOperation(request);
           //         System.err.print("Adding on DB OK");         
                } catch (Exception ex) {
                    // TODO handle custom exceptions here
                    System.err.print("Adding on DB ERROR"+ex.getLocalizedMessage());         
                }
			
		
	}

    public UIData getOdocs() {
        return odocs;
    }

    public void setOdocs(UIData odocs) {
        this.odocs = odocs;
    }

    public ArrayList<cdocumentlist> getAdocs() {
        PopulateList();
        return adocs;
    }

    public void setAdocs(ArrayList<cdocumentlist> adocs) {
        this.adocs = adocs;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public

    //String szPath = "/applications/AppServers/jboss-4.0.3SP1/server/default/deploy/";
    String getSzPath() {
        return szPath;
    }

    public void setSzPath(String szPath) {
        this.szPath = szPath;
    }

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
    public void upl()
    {
    // Just to demonstrate what information you can get from the uploaded file.
       // System.err.println("File type: " + uploadedFile.getContentType());
       // System.err.println("File name: " + uploadedFile.getName());
       // System.err.println("File size: " + uploadedFile.getSize() + " bytes");

        try {
            // Precreate an unique file and then write the InputStream of the uploaded file to it.
            //System.err.println("make filename");
            File uniqueFile = new File(szPath+FileUtil.trimFilePath(uploadedFile.getName()));//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            //System.err.println("write");
            FileUtil.write(uniqueFile, uploadedFile.getInputStream());
            //System.err.println("get unique filename");
            filename = uniqueFile.getName();
            //AddToTech();
            //System.err.println("call add to list");
            addToListdocs();
            // Show succes message.
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
            //System.err.println("File upload ok size: " + uploadedFile.getSize() + " bytes");
            
        } catch (IOException e) {

            // Show error message.
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
System.err.println("File upload fail");
            // Always log stacktraces.
            e.printStackTrace();
        }
    }
    
    public void removep() {
        
		for (int i=0; i<adocs.size(); i++) {
			cdocumentlist ps = adocs.get(i);
			if (ps.isBselected()) {
				
                            File ftemp= new File(ps.getFilename());
                            ftemp.delete();
                            
                            try { // Call Web Service Operation
                                org.ellectra.wscdm.CdocumentPortType port = service.getCdocumentPort();

                                org.ellectra.wscdm.Request request = new org.ellectra.wscdm.Request();
                                request.setAction("DELETEDOCUMENT");
                    request.setCftid(1);
                    request.setDesc("desc");
                    request.setFilename("filename");
                    request.setLanguage("language");
                    String sdoctype=filename.substring(filename.length()-3, filename.length());
                    request.setMime(sdoctype);
                    request.setType(sdoctype);
                    request.setStatus("UPLOAD");
                    XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
                    request.setTimestamp(calendar);
                    request.setUserid(Integer.valueOf(dUserloginid).intValue());
                    request.setSignature(dUserloginsignature);
                    request.setDocid(ps.getIcid());
                                org.ellectra.wscdm.Response result = port.cdocumentOperation(request);
                                
                            } catch (Exception ex) {
                                // TODO handle custom exceptions here
                            }

                            
                            adocs.remove(ps);
	
			}
		}
		
		
		
		
	}
    
    public String DownloadDocumentButton() {
//  String dValue=(String) FacesContext.getCurrentInstance().getExternalContext()
  //          .getRequestParameterMap().get("documentpathname");
 

  ///////////////////////////////////
  
   // Prepare.
//        File pdfFile = new File("c:\\dd.txt");
//        FacesContext context = FacesContext.getCurrentInstance();
//        HttpServletResponse response = 
//            (HttpServletResponse) context.getExternalContext().getResponse();
//
//        // Download file.
//        try {
//            HttpServletUtil.downloadFile(response, pdfFile, true);     
//        } catch (IOException e) {
//            // Do your error handling thing.
//         //   setErrorMessage("Download file failed: " + e.getMessage());
//            e.printStackTrace();
//            return null;
//        }
//
//        // Prevent other JSF lifecycle phases eventually being invoked.
//        // Otherwise you can get the following exception:
//        // java.lang.IllegalStateException: Cannot forward after response has been committed.
//        context.responseComplete();

  //////////////////////////////////
            return null;
    }
    
    public static byte[] getByteData (String path) {
            byte[] result = null;
            try {
                    byte[] temp = new byte[1024];
                    int len = 0;
                    FileInputStream inputFile = new FileInputStream (path);
                    ByteArrayOutputStream outputFile = new ByteArrayOutputStream();
                    while (inputFile.available() != 0) {
                            len = inputFile.read(temp);
                            outputFile.write(temp, 0, len);
                    }
                    inputFile.close();
                    result = outputFile.toByteArray();
            } catch (Exception e) {
                    e.printStackTrace();
            }
            return result;
    }
    
    public String downloadDocument() {
        String downfilename = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("downfilename");
        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "FILENAME", downfilename);
        System.err.println("File to download is: " + downfilename);
        
        FacesContext ctx = FacesContext.getCurrentInstance();

        String result="error";
        
        if (!ctx.getResponseComplete()) {
            //String serverDir = "/Users/gpa/filesToBeDownloaded/";
            String filePath = szPath + downfilename; 
            //"\"Users\"gpa\"filesToBeDownloaded\"" +
            //myFileName.txt
            byte[] out = getByteData(filePath);
            
            try{
                HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
                //response.setHeader("Content-Disposition","attachment;downfilename=\"" + file + "\""); 
                response.setContentType("application/x-download");
                //application/octet-stream
                //application/x-download
                //application/pdf
                response.setHeader("Content-Disposition","attachment; filename=" + downfilename);
                response.setContentLength(out.length);
                
                ServletOutputStream sos = response.getOutputStream(); 

                sos.write(out);
                sos.flush();
                sos.close();

                ctx.responseComplete();
                
                result="ok";
                return result;
            }catch (FileNotFoundException e) {
                System.err.println("Download file failed, file not found");
                e.printStackTrace();
                result="error";
                return result;
            } catch (IOException e) {
                System.err.println("Download file failed, I/O error");
                e.printStackTrace();
                result="error";
                return result;
            } catch (Exception e) { 
                System.err.println("Exception"); 
                e.printStackTrace();
                result="error";
                return result;
            } 
        }
        return result;
    }
    
    
    
}