/*
 * 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.GregorianCalendar;
import java.util.TimeZone;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
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.fileutils.FileUtil;
import org.ellectra.gui.utils.JSFUtils;
import org.ellectra.wsad.AdditionaldocumentService;

/**
 *
 * @author tdi
 */
public class additionaldocuments {

    
    @WebServiceRef(wsdlLocation = "http://localhost:18181/additionaldocumentService/additionaldocumentPort?wsdl")
    private AdditionaldocumentService service;
    
    private String filename;
    private UIData addata = null;
    private ArrayList<org.ellectra.gui.managebeans.additionaldocumentlist> adocsl = new ArrayList();
    
    String dUserloginname;
    String dUserloginsignature;
    String dUserloginOrganization;
    String dUserloginrole;
    String dUserlogintenderid;
    String dUserloginid;
    int mytenderid;
    int iuseridlogin;
    int seid;
    private String sznewrtitle;
    private String sznewrtext;
    
    private String awtest;
    private String awdate;
    private String awfile;
    private String awuser;
    
    private String qutitle;
    private String qudesc;
    private String qudate;
    private String quser;
    
    private String newreplydesc;
    private String ssslang;
    private String replyawsntext;
    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/";
    
    public additionaldocuments()
    {
        super();
        pathSettings dset=new pathSettings();
        szPath=dset.GetUploadDirectory();
        
    }
    
    // Actions ------------------------------------------------------------------------------------
    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");
        if (dtemp != null)
        mytenderid = Integer.valueOf(dtemp).intValue();
        if (dUserloginid != null)
        iuseridlogin = Integer.valueOf(dUserloginid).intValue(); 
    }
    
    
    public String goBack() {
        java.lang.String Eo = (java.lang.String) org.ellectra.gui.utils.JSFUtils.retrieveOnSession(javax.faces.context.FacesContext.getCurrentInstance(), "LOGINROLEEO");

        if (Eo.equalsIgnoreCase("EO"))
            return "backToCalleo";
        else
            return "backToCall";
    }

    /**
     * Function used to populate the table in Additional documents tab
     * @return
     */
    public ArrayList<additionaldocumentlist> getAdocsl() {
        GetSessionVariables();
        adocsl.clear();
        //GetSessionVariables();
        //System.err.print("Called get requestes");
        try { // Call Web Service Operation
            org.ellectra.wsad.AdditionaldocumentPortType port = service.getAdditionaldocumentPort();

            org.ellectra.wsad.Request part1 = new org.ellectra.wsad.Request();
            //  System.err.print("2");
            part1.setAction("QUERYQ");
            part1.setUid(iuseridlogin);
            part1.setCalloftenderid(mytenderid);
            part1.setSignature(dUserloginsignature);
            org.ellectra.wsad.Response result = port.additionaldocumentOperation(part1);
            
            //org.ellectra.wscdm.Response result = port.cdocumentOperation(request);
            for (int i = 0; i < result.getReturnlist().size(); i++) {
                
                org.ellectra.wsad.Response.Returnlist ditem = result.getReturnlist().get(i);
                if (ditem.getTitle().equalsIgnoreCase("NULLNA")) {
                    
                } else {
                    additionaldocumentlist e = new additionaldocumentlist();
                    //org.ellectra.wsad.Response.Returnlist ditem= result.getReturnlist().get(i);
                    //   System.err.print("Found request"+i);
//               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()); 
//                
//                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()); 
//                
//               e.setCreationdate(currentTime);
//               e.setPublicationdate(currentTime2);
//               e.setFilename(ditem.getFilename());
//               e.setLanguage(ditem.getLanguage());
//               e.setIcid(ditem.getDocid());
//               e.setTitle(ditem.getDesc());
//               e.setMime(ditem.getMime());
//               e.setType(ditem.getType());
                    e.setDawn(ditem.getAnswered());

                    /// need that
                    GregorianCalendar g2 = ditem.getDatereceived().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());
                    e.setDsent(currentTime2);
                    /////////////

                    e.setRid(ditem.getRid());
                    e.setTid(ditem.getTid());
                    e.setTitle(ditem.getTitle());
                    e.setDesc(ditem.getText());
                    e.setFirstName(ditem.getFirstName());
                    e.setLastName(ditem.getLastName());
                    adocsl.add(e);
                }
            }

        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.err.print("Error on get questions: " + ex.getLocalizedMessage());
        }


        return adocsl;
    }

    /**
     * Function used to create a new record in table Question
     * @return
     */
    public String AddRequest() {
        //System.err.println("Add Reading Variables ");
        GetSessionVariables();
        // sznewrtitle="ddddddd";
        // sznewrtext="user"+iuseridlogin+"tender"+mytenderid+"signature"+dUserloginsignature;
        try { 
            org.ellectra.wsad.AdditionaldocumentPortType port = service.getAdditionaldocumentPort();

            //    System.err.println("Add start ");
            org.ellectra.wsad.Request part1 = new org.ellectra.wsad.Request();
            part1.setAction("ADDQ");
            part1.setUid(iuseridlogin);
            part1.setCalloftenderid(mytenderid);
            part1.setQid(mytenderid);
            part1.setSignature(dUserloginsignature);
            part1.setDesc(sznewrtext);
            part1.setSubject(sznewrtitle);
            //  System.err.println("Add do calendar ");
            XMLGregorianCalendar calendar =
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(
                    new GregorianCalendar());
//           System.err.println("Add set calendar ");
            part1.setDatec(calendar);
            //         System.err.println("Add do operation ");
            
            org.ellectra.wsad.Response result = port.additionaldocumentOperation(part1);
            System.err.println("Result OK " + result.getMessage());
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.err.print("error" + ex.getLocalizedMessage() + ex.getMessage());
        }

        return "OK";
    }
    
    /**
     * Function used to create a new record in table Answer
     * @return
     */
    public String AddReply() {
        GetSessionVariables();

        //qutitle=Selected.getTitle();
        //qudesc=Selected.getDesc();
        //qudate=Selected.getDsent();
        
        try { 
            //System.err.println("trye to add reply");
            org.ellectra.wsad.AdditionaldocumentPortType port = service.getAdditionaldocumentPort();

            org.ellectra.wsad.Request part1 = new org.ellectra.wsad.Request();
            part1.setAction("CREATEA");
            //System.out.println("reply 1");
            part1.setUid(iuseridlogin);
            part1.setCalloftenderid(mytenderid);
            part1.setSignature(dUserloginsignature);
            //part1.setDesc(newreplydesc);
            part1.setAttachment(filename);
            part1.setLang(ssslang);
            part1.setMime(filename.substring(filename.length() - 3, filename.length()));
            
            //answer
            part1.setDesc(replyawsntext);
            //file,language,mime
            //part1.setSubject(sznewrtitle);
            part1.setQid(seid);
            System.err.println("user id: " + iuseridlogin);
            System.err.println("call id: " + mytenderid);
            System.err.println("signature: " + dUserloginsignature);
            System.err.println("question id: " + seid);
            System.err.println("answer text: " + replyawsntext);
            System.err.println("attachment filename: " + filename);
            System.err.println("attachment lang: " + ssslang);
            
            
            
            XMLGregorianCalendar calendar =
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(
                    new GregorianCalendar());
            part1.setDatec(calendar);
            //System.out.println("reply ok do add");
            
            org.ellectra.wsad.Response result = port.additionaldocumentOperation(part1);
        //System.out.println("reply Result = "+result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.err.println("error on reply" + ex.getLocalizedMessage() + ex.getMessage());
        }

        return "backToCall";
    }
    
    /**
     * Function used to populate fields for an answer on a given question
     */
    public void Loadaw() {
        GetSessionVariables();

        try { // Call Web Service Operation
            org.ellectra.wsad.AdditionaldocumentPortType port = service.getAdditionaldocumentPort();

            org.ellectra.wsad.Request part1 = new org.ellectra.wsad.Request();
            part1.setAction("QUERYA");
            part1.setUid(iuseridlogin);
            part1.setCalloftenderid(mytenderid);
            part1.setSignature(dUserloginsignature);
            part1.setQid(seid);
            System.err.println("user id: " + iuseridlogin);
            System.err.println("call id: " + mytenderid);
            System.err.println("signature: " + dUserloginsignature);
            System.err.println("question id: " + seid);
            
            
            org.ellectra.wsad.Response result = port.additionaldocumentOperation(part1);
            System.err.println("answers returned: " + result.getReturnlist().size());
            
            for (int i=0; i< result.getReturnlist().size(); i++) {
                if (!(result.getReturnlist().get(i).getTitle()).equals("NULLNA") ) {
                    awtest = result.getReturnlist().get(i).getText();
                    awfile = result.getReturnlist().get(i).getAttachment();
                    awuser = result.getReturnlist().get(i).getFirstName() + " " + result.getReturnlist().get(i).getLastName();

                    GregorianCalendar g2 = result.getReturnlist().get(i).getDatereceived().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());
                    awdate = currentTime2;
                }
                else {
                    awtest = "";
                    awfile = "";
                    awuser = "";
                    awdate = "";
                }
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
            // TODO handle custom exceptions here
        }
    }

    /**
     * Function to read details on a specific request
     * @return
     */
    public String ReadAndReply(/*ActionEvent event*/) {
        additionaldocumentlist Selected = (additionaldocumentlist) this.getAddata().getRowData();
        seid = Selected.getRid();
        qutitle = Selected.getTitle();
        qudesc = Selected.getDesc();
        qudate = Selected.getDsent();
        quser = Selected.getFirstName() + " " + Selected.getLastName();
        
        Loadaw();

        //System.err.println("You have pressed some button: "+Selected.getOrganizationname());
        //OK
        return "readandreply";
    }

    public String ReplyOnRequest(/*ActionEvent event*/) {
        additionaldocumentlist Selected = (additionaldocumentlist) this.getAddata().getRowData();
        seid = Selected.getRid();
        qutitle = Selected.getTitle();
        qudesc = Selected.getDesc();
        qudate = Selected.getDsent();
        
        Loadaw();
        //
        //System.err.println("You have pressed some button: "+Selected.getOrganizationname());
        return "replyrequest";
    }

    public String AddReply2() {
        //System.err.println("IN");
        GetSessionVariables();

        try { // Call Web Service Operation
            // System.err.println("trye to add reply");
            org.ellectra.wsad.AdditionaldocumentPortType port = service.getAdditionaldocumentPort();

            org.ellectra.wsad.Request part1 = new org.ellectra.wsad.Request();
            part1.setAction("CREATEA");
            //System.out.println("reply 1");
            part1.setUid(iuseridlogin);
            part1.setCalloftenderid(mytenderid);
            part1.setSignature(dUserloginsignature);
            //part1.setDesc(newreplydesc);
            part1.setAttachment("sdfsdfsdfsdsdf");
            part1.setLang(ssslang);
            part1.setMime("TEXT_PLAIN");
            part1.setDesc(replyawsntext);
            //file,language,mime
            //part1.setSubject(sznewrtitle);
            part1.setQid(seid);
            //System.out.println("reply 2");
            XMLGregorianCalendar calendar =
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(
                    new GregorianCalendar());
            part1.setDatec(calendar);
            //System.out.println("add reply ok do add");
            org.ellectra.wsad.Response result = port.additionaldocumentOperation(part1);
        //System.out.println("add reply Result = "+result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.err.println("error on reply" + ex.getLocalizedMessage() + ex.getMessage());
        }

        return "OK";
    }
    
    public void uploadAttachment () {
        //additionaldocumentlist Selected= (additionaldocumentlist) this.getAddata().getRowData();
        //seid=Selected.getRid();
        // Just to demonstrate what information you can get from the uploaded file.
        //System.err.println("File type: " + getUploadedFile().getContentType());
        //System.err.println("File name: " + getUploadedFile().getName());
        //System.err.println("File size: " + getUploadedFile().getSize() + " bytes");

        try {
            // Precreate an unique file and then write the InputStream of the uploaded file to it.
            File uniqueFile = new File(szPath + FileUtil.trimFilePath(getUploadedFile().getName()));//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            FileUtil.write(uniqueFile, getUploadedFile().getInputStream());
            filename = uniqueFile.getName();
            //addToListdocs();
            // Show succes message.
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                    FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
        //  System.err.println("File upload ok size: " + getUploadedFile().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.
            //OK
            //OK
            //OK
            //OK
            e.printStackTrace();
        }
        
    }
    
    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;
    }

    
    public void getContentType() {
//       ServletOutputStream out = _res.getOutputStream();
//        if(fileExt.equalsIgnoreCase(".pdf")) //check the out type
//        contentType = "application/pdf";
//        else if(fileExt.equalsIgnoreCase(".gif"))
//        contentType = "image/gif";
//        else if(fileExt.equalsIgnoreCase(".jpg"))
//        contentType = "image/jpeg";
//        else if(fileExt.equalsIgnoreCase(".bmp"))
//        contentType = "image/bmp";
//        else if(fileExt.equalsIgnoreCase(".png"))
//        contentType = "image/x-png";
//        else if(fileExt.equalsIgnoreCase(".doc"))
//        contentType = "application/mdword";
//        else if(fileExt.equalsIgnoreCase(".xls"))
//        contentType = "application/vnd.ms-excel";
//        else if( fileExt.equalsIgnoreCase(".html") || fileExt.equalsIgnoreCase(".htm"))
//        contentType = "text/html";
//        else if(fileExt.equalsIgnoreCase(".xml"))
//        contentType = "text/xml";
//        else if (fileExt.equalsIgnoreCase(".ppt") || fileExt.equalsIgnoreCase(".pps") )
//        contentType = "application/mspowerpoint";
//        else if (fileExt.equalsIgnoreCase(".zip"))
//        //contentType = "application/zip";
//        contentType = "application/x-zip-compressed";
//        else if (fileExt.equalsIgnoreCase(".ps"))
//        contentType = "application/postscript";
//        else if (fileExt.equalsIgnoreCase(".exe"))
//        contentType = "application/octet-stream";
//        else if (fileExt.equalsIgnoreCase(".gz"))
//        contentType = "application/x-gzip";
//        else if (fileExt.equalsIgnoreCase(".txt"))
//        contentType = "text/plain";
//        else
//            contentType = "application/octet-stream";
//        contentType += ";charset=iso-8859-7";
//        _res.setContentType(contentType);
//        _res.setHeader("Content-disposition", "attachment; filename=" + fileName); 
    }

    public String getAwtest() {
        return awtest;
    }

    public void setAwtest(String awtest) {
        this.awtest = awtest;
    }

    public String getAwdate() {
        return awdate;
    }

    public void setAwdate(String awdate) {
        this.awdate = awdate;
    }

    public String getAwfile() {
        return awfile;
    }

    public void setAwfile(String awfile) {
        this.awfile = awfile;
    }

    public String getQutitle() {
        return qutitle;
    }

    public void setQutitle(String qutitle) {
        this.qutitle = qutitle;
    }

    public String getQudesc() {
        return qudesc;
    }

    public void setQudesc(String qudesc) {
        this.qudesc = qudesc;
    }

    public String getQudate() {
        return qudate;
    }

    public void setQudate(String qudate) {
        this.qudate = qudate;
    }

    public String getNewreplydesc() {
        return newreplydesc;
    }

    public void setNewreplydesc(String newreplydesc) {
        this.newreplydesc = newreplydesc;
    }

    public String getSsslang() {
        return ssslang;
    }

    public void setSsslang(String ssslang) {
        this.ssslang = ssslang;
    }

    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public String getReplyawsntext() {
        return replyawsntext;
    }

    public void setReplyawsntext(String replyawsntext) {
        this.replyawsntext = replyawsntext;
    }

    public UIData getAddata() {
        return addata;
    }

    public void setAddata(UIData addata) {
        this.addata = addata;
    }

    public void setAdocsl(ArrayList<additionaldocumentlist> adocsl) {
        this.adocsl = adocsl;
    }

    public String getSznewrtitle() {
        return sznewrtitle;
    }

    public void setSznewrtitle(String sznewrtitle) {
        this.sznewrtitle = sznewrtitle;
    }

    public String getSznewrtext() {
        return sznewrtext;
    }

    public void setSznewrtext(String sznewrtext) {
        this.sznewrtext = sznewrtext;
    }

    public String getQuser() {
        return quser;
    }

    public void setQuser(String quser) {
        this.quser = quser;
    }

    public String getAwuser() {
        return awuser;
    }

    public void setAwuser(String awuser) {
        this.awuser = awuser;
    }


    
}
