/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ellectra.gui.managebeans;

import java.io.File;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;

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.wsproposaldocs.ProposalDocumentManagementService;
import org.ellectra.wsst.SubmissionOfTenderService;
import org.ellectra.wsviewmytends.ViewMyTendersService;

/**
 *
 * @author tdi
 */
public class submittender {
    @WebServiceRef(wsdlLocation = "http://localhost:8080/ProposalDocumentManagementService/ProposalDocumentManagement?wsdl")
    private ProposalDocumentManagementService service_2;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/ViewMyTendersService/ViewMyTendersPort?wsdl")
    private ViewMyTendersService service_1;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/SubmissionOfTenderService/SubmissionOfTenderPort?wsdl")
    private SubmissionOfTenderService service;
    // Init ---------------------------------------------------------------------------------------
    private UIData pdata = null;
    private UIData tdata = null;
    private UIData fdata = null;
    private ArrayList<prooflist> pdoc = new ArrayList();
    private ArrayList<techlist> tdoc = new ArrayList();
    private ArrayList<finalist> fdoc = new ArrayList();
    private UploadedFile uploadedFile;
    private String fileName;
    private String desc;
    private String language;
    // String szPath = "/applications/AppServers/jboss-4.0.3SP1/server/default/deploy/";
//    String szPath ="c:\\upload\\";
//    String szPathb ="c:\\windows\\";
    String szPath = "/Users/gpa/upload/";   //not need initial values now //
    String szPathb = "/Users/gpa/uploadb/";
    
    String dUserloginname;
    String dUserloginsignature;
    String dUserloginOrganization;
    String dUserloginrole;
    String dUserlogintenderid;
    String dUserloginid;
    int mytenderid;
    int mycallid;
    
    private String btnUploadTechDisabled;
    private String btnUploadFinadisabled;
    private boolean renderDeleteText;
    private String btnSubmitDisabled;
    private ArrayList<techlist> removedTechIDs = new ArrayList();
    private ArrayList<finalist> removedFinaIDs = new ArrayList();
    
    public submittender()
    {
        super();
        pathSettings dset=new pathSettings();
        szPath=dset.GetUploadDirectory();
        szPathb=dset.GetUploadbDirectory();
    }
    // 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(), "TENDERIDI");
        mytenderid = Integer.valueOf(dtemp).intValue();
        String selectedCall = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID");
        mycallid = Integer.valueOf(selectedCall).intValue();
        
    }

    private void reset() {
        pdoc.clear();
        tdoc.clear();
        fdoc.clear();
        
        getRemovedTechIDs().clear();
        getRemovedFinaIDs().clear();
    }
    
    public String formatFilename(String filepath){
        int lastSlash = filepath.lastIndexOf("/");
        return filepath.substring(lastSlash + 1, filepath.length());
    }

    public void removep() {
        GetSessionVariables();
        for (int i = 0; i < pdoc.size(); i++) {
            prooflist ps = pdoc.get(i);
            if (ps.isSelected()) {
                pdoc.remove(ps);
                try { // Call Web Service Operation
                    org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

                    org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
                    request.setAction("REMOVESERVER");
                    request.setDoctype("1");
                    request.setFile(ps.getFilename());
                    request.setPath(szPath);
                    request.setOrganization(dUserloginOrganization);
                    request.setRole(dUserloginrole);
                    request.setSignature(dUserloginsignature);
                    request.setTenderid(dUserlogintenderid);
                    request.setUsername(dUserloginname);
                    request.setDescription(ps.getDescription());
                    request.setLanguage(ps.getLanguage());
                    org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);

                } catch (Exception ex) {
                    // TODO handle custom exceptions here
                    //OK
                }
            }
        }

    }

    public void removef() {
        GetSessionVariables();
        for (int i = 0; i < fdoc.size(); i++) {
            finalist ps = fdoc.get(i);
            if (ps.isSelected()) {
                getRemovedFinaIDs().add(ps);
                fdoc.remove(ps);
                try { // Call Web Service Operation
                    org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

                    org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
                    request.setAction("REMOVESERVER");
                    request.setDoctype("3");
                    request.setFile(ps.getFilename());
                    request.setPath(szPath);
                    request.setOrganization(dUserloginOrganization);
                    request.setRole(dUserloginrole);
                    request.setSignature(dUserloginsignature);
                    request.setTenderid(dUserlogintenderid);
                    request.setUsername(dUserloginname);
                    request.setDescription(ps.getDescription());
                    request.setLanguage(ps.getLanguage());
                    org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);

                } catch (Exception ex) {
                    // TODO handle custom exceptions here
                    //OK
                }
            }
        }

    }

    public void removet() {
        GetSessionVariables();
        for (int i = 0; i < tdoc.size(); i++) {
            techlist ps = tdoc.get(i);
            if (ps.isSelected()) {
                getRemovedTechIDs().add(ps);
                tdoc.remove(ps);
                try { // Call Web Service Operation
                    org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

                    org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
                    request.setAction("REMOVESERVER");
                    request.setDoctype("2");
                    request.setFile(ps.getFilename());
                    request.setPath(szPath);
                    request.setOrganization(dUserloginOrganization);
                    request.setRole(dUserloginrole);
                    request.setSignature(dUserloginsignature);
                    request.setTenderid(dUserlogintenderid);
                    request.setUsername(dUserloginname);
                    request.setDescription(ps.getDescription());
                    request.setLanguage(ps.getLanguage());
                    org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);

                } catch (Exception ex) {
                    // TODO handle custom exceptions here
                }
            }
        }

    }

    /**
     * This function is used primarly to SUBMIT on the server the Proof document given. 
     * also, adds an uploaded Proof Document in the list of proof docs.
     */
    public void AddToProof() {
        GetSessionVariables();
        
        prooflist ditem = new prooflist();
        ditem.setDescription(desc);
        ditem.setLanguage(language);
        ditem.setFilename(fileName);
        pdoc.add(ditem);

        try { 
            org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

            org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
            request.setAction("SERVERSIDE");
            request.setDoctype("1");
            request.setFile(fileName);
            request.setPath(szPath);
            request.setOrganization(dUserloginOrganization);
            request.setRole(dUserloginrole);
            request.setSignature(dUserloginsignature);
            request.setTenderid(dUserlogintenderid);
            request.setUsername(dUserloginname);
            request.setDescription(desc);
            request.setLanguage(language);
            org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);
            
            desc = "";

        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }

    }

    /**
     * This function is used primarly to SUBMIT on the server the Technical document given. 
     * also, adds an uploaded Technical Document in the list of tech docs.
     */
    public void AddToTech() {
        GetSessionVariables();
        
        techlist ditem = new techlist();
        ditem.setId(0); //means not related to a tender yet
        ditem.setDescription(desc);
        ditem.setLanguage(language);
        ditem.setFilename(fileName);
        tdoc.add(ditem);
        
        try { 
            org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

            org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
            request.setAction("SERVERSIDE");
            request.setDoctype("2");
            request.setFile(fileName);
            request.setPath(szPath);
            request.setOrganization(dUserloginOrganization);
            request.setRole(dUserloginrole);
            request.setSignature(dUserloginsignature);
            request.setTenderid(dUserlogintenderid);
            request.setUsername(dUserloginname);
            request.setDescription(desc);
            request.setLanguage(language);
            org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);
            
            desc = "";

        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
        
    }

    /**
     * This function This function is used primarly to SUBMIT on the server the Financial document given. 
     * also, adds an uploaded Financial Document in the list of fina docs.
     */
    public void AddToFina() {
        GetSessionVariables();
        
        finalist ditem = new finalist();
        ditem.setId(0); //means not related to a tender yet
        ditem.setDescription(desc);
        ditem.setLanguage(language);
        ditem.setFilename(fileName);
        fdoc.add(ditem);
        
        try { 
            org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

            org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
            request.setAction("SERVERSIDE");
            request.setDoctype("3");
            request.setFile(fileName);
            request.setPath(szPath);
            request.setOrganization(dUserloginOrganization);
            request.setRole(dUserloginrole);
            request.setSignature(dUserloginsignature);
            request.setTenderid(dUserlogintenderid);
            request.setUsername(dUserloginname);
            request.setDescription(desc);
            request.setLanguage(language);
            org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);
            
            desc = "";

        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
        
    }

    /**
     * Function called to store a Proof Document on the server
     */
    public void submit() {

        // 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.
            File uniqueFile = new File(szPath + FileUtil.trimFilePath(uploadedFile.getName()));//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            File uniqueFileb = new File(szPathb + FileUtil.trimFilePath(uploadedFile.getName()) + "b");//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            
            FileUtil.write(uniqueFile, uploadedFile.getInputStream());
            FileUtil.write(uniqueFileb, uploadedFile.getInputStream());
            
            fileName = uniqueFile.getName();
            //Do the actual storing (encrypt, timestamp etc.)
            AddToProof();
            
            // 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();
        }
    }

    /**
     * Function called to store a Technical Document on the server
     */
    public void submitt() {

        // 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.
            File uniqueFile = new File(szPath + FileUtil.trimFilePath(uploadedFile.getName()));//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            File uniqueFileb = new File(szPathb + FileUtil.trimFilePath(uploadedFile.getName()) + "b");//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            
            FileUtil.write(uniqueFile, uploadedFile.getInputStream());
            FileUtil.write(uniqueFileb, uploadedFile.getInputStream());
            
            fileName = uniqueFile.getName();
            //Do the actual storing (encrypt, timestamp etc.)
            AddToTech();
            
            // 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();
        }
    }

    /**
     * Function called to store a Financial Document on the server
     */
    public void submitf() {

        // 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.
            File uniqueFile = new File(szPath + FileUtil.trimFilePath(uploadedFile.getName()));//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            File uniqueFileb = new File(szPathb + FileUtil.trimFilePath(uploadedFile.getName()) + "b");//FileUtil.uniqueFile(new File("c:\\upload"), uploadedFile.getName());
            
            FileUtil.write(uniqueFile, uploadedFile.getInputStream());
            FileUtil.write(uniqueFileb, uploadedFile.getInputStream());
            
            fileName = uniqueFile.getName();
            //Do the actual storing (encrypt, timestamp etc.)
            AddToFina();
            
            // 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();
        }
    }

    private int SubmitTenderDocument(String vdoctype, String vfilename, String vdesc, String vlanguage) {
        GetSessionVariables();
        int idCreated = 0;
        try { // Call Web Service Operation
            org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

            org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
            request.setAction("SUBMITTENDER");
            request.setDoctype(vdoctype);
            request.setFile(vfilename);
            request.setPath(szPath);
            request.setOrganization(dUserloginOrganization);
            request.setRole(dUserloginrole);
            request.setSignature(dUserloginsignature);
            request.setTenderid(dUserlogintenderid);
            request.setUsername(dUserloginname);
            request.setDescription(vdesc);
            request.setLanguage(vlanguage);
            request.setTenderidint(mytenderid);
            System.err.println("-------SUBMISSION INPUT-------");
            System.err.println("1: " + vdoctype);
            System.err.println("2: " + vfilename);
            System.err.println("3: " + szPath);
            System.err.println("4: " + dUserloginOrganization);
            System.err.println("5: " + dUserloginrole);
            System.err.println("6: " + dUserloginsignature);
            System.err.println("7: " + dUserlogintenderid);
            System.err.println("8: " + dUserloginname);
            System.err.println("9: " + vdesc);
            System.err.println("10: " + vlanguage);
            System.err.println("11: " + mytenderid);
            System.err.println("-------SUBMISSION END-------");
            
            org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);
            
            idCreated = Integer.valueOf(result.getId()).intValue();
            System.err.println("CREATED ID: " + idCreated);
            
            return idCreated;
        } catch (Exception ex) {
            System.err.println("SUBMISSION EXCEPTION");
            ex.printStackTrace();
            return 0;
        }

    }

    /**
     * Function used to create or delete records in Proposal Document table
     * @return
     */
    public String SubmitTender() {
        boolean dret = true;
        int[] techInfo = new int[15];
        int[] finaInfo = new int[15];
        
        //1) remove any old records
        if (!removedTechIDs.isEmpty()){
            for (int j = 0; j < getRemovedTechIDs().size(); j++) {
                techlist toRemove = getRemovedTechIDs().get(j);
                int id = toRemove.getId();
                if (id != 0)
                    deleteDocumentRecord(id);
            }
        }
        if (!removedFinaIDs.isEmpty()){
            for (int j = 0; j < getRemovedFinaIDs().size(); j++) {
                finalist toRemove = getRemovedFinaIDs().get(j);
                int id = toRemove.getId();
                if (id != 0)
                    deleteDocumentRecord(id);
            }
        }
        
        //2) create new technical record
        if (!tdoc.isEmpty()) {
            for (int i = 0; i < tdoc.size(); i++) {
                techlist ps = tdoc.get(i);
                //create technical record only if it does not exist
                System.err.println("item ID: " + ps.getId());
                if (ps.getId() == 0) {
                    int res = SubmitTenderDocument("2", ps.getFilename(), ps.getDescription(), ps.getLanguage());
                    if (res == 0) {
                        dret = false;
                        techInfo[i] = 0;
                    }
                    else
                        techInfo[i] = res;
                    System.err.println("techinfo[i]: " + res);
                }
            }
        }
        //3) create new financial record
        if (!fdoc.isEmpty()) {
            for (int i = 0; i < fdoc.size(); i++) {
                finalist ps = fdoc.get(i);
                //create financial record only if it does not exist
                System.err.println("item ID: " + ps.getId());
                if (ps.getId() == 0) {
                    int res = SubmitTenderDocument("3", ps.getFilename(), ps.getDescription(), ps.getLanguage());
                    if (res == 0) {
                        dret = false;
                        finaInfo[i] = 0;
                    }
                    else
                        finaInfo[i] = res; 
                    System.err.println("finainfo[i]: " + res);
                }
            }
        }
        
        
        //4) check data integrity between submitted file and record associating this file to tender
        if (!tdoc.isEmpty()) {
            for (int i = 0; i < tdoc.size(); i++) {
                techlist ps = tdoc.get(i);
                String filename = ps.getFilename();
                File file = new File(szPath + filename);
                boolean exists = file.exists();
                if (!exists) {
                    System.err.println("File not exist");
                    if (techInfo[i] != 0) 
                        deleteDocumentRecord(techInfo[i]);
                }
            }
        }
        if (!fdoc.isEmpty()) {
            for (int i = 0; i < fdoc.size(); i++) {
                finalist ps = fdoc.get(i);
                String filename = ps.getFilename();
                File file = new File(szPath + filename);
                boolean exists = file.exists();
                if (!exists) {
                    System.err.println("File not exist");
                    if (finaInfo[i] != 0) 
                        deleteDocumentRecord(finaInfo[i]);
                }
            }
        }
        
        reset();
        if (dret == true) 
            return "success";
        else
            return "failure";

    }
    
    private void deleteDocumentRecord(int idToDelete) {
       try { 
           org.ellectra.wsproposaldocs.ProposalDocumentManagement port = service_2.getProposalDocumentManagementPort();
                 // TODO initialize WS operation arguments here
                //java.lang.Integer arg0 = Integer.valueOf(0);// TODO process result here
           boolean result = port.deleteProposalDocument(idToDelete);
           System.err.println("DELETED? = "+result);
        } catch (Exception ex) {
           System.err.println("DELETION EXCEPTION");
            ex.printStackTrace();
        }
            
       
    }
    
    
    private boolean compare(Object sourceObj, Object targetObj, int comparison) {
        int id1 = 0;
        int id2 = 0;
        String file1 = "";
        String file2 = "";
        String descr1 = "";
        String descr2 = "";
        String lang1 = "";
        String lang2 = "";
        String tms1 = "";
        String tms2 = "";
        
        
        if (comparison == 0) {
            id1 = ((techlist)sourceObj).getId();
            file1 = ((techlist)sourceObj).getFilename().trim();
            descr1 = ((techlist)sourceObj).getDescription().trim();
            lang1 = ((techlist)sourceObj).getLanguage().trim();
            //tms1 = ((techlist)sourceObj).getTimestamp().trim();
            id2 = ((techlist)targetObj).getId();
            file2 = ((techlist)targetObj).getFilename().trim();
            descr2 = ((techlist)targetObj).getDescription().trim();
            lang2 = ((techlist)targetObj).getLanguage().trim();
            //tms2 = ((techlist)targetObj).getTimestamp().trim();
        }
        else if (comparison == 1) {
            id1 = ((finalist)sourceObj).getId();
            file1 = ((finalist)sourceObj).getFilename().trim();
            descr1 = ((finalist)sourceObj).getDescription().trim();
            lang1 = ((finalist)sourceObj).getLanguage().trim();
            //tms1 = ((finalist)sourceObj).getTimestamp().trim();
            id2 = ((finalist)targetObj).getId();
            file2 = ((finalist)targetObj).getFilename().trim();
            descr2 = ((finalist)targetObj).getDescription().trim();
            lang2 = ((finalist)targetObj).getLanguage().trim();
            //tms2 = ((finalist)targetObj).getTimestamp().trim();
        }
        return ( (id1 == id2) && (file1.equals(file2)) && (descr1.equals(descr2)) && (lang1.equals(lang2)) );//&& (tms1.equals(tms2)) ); 
    }
    
   private boolean contains(Object element, ArrayList list) {
        boolean result = false;
        if (!list.isEmpty()) {
            int comparison = 0;
            if (element instanceof finalist)
                comparison = 1;

            for (int j = 0; j < list.size(); j++) {
                Object listObj = list.get(j);
                boolean found = compare(element, listObj, comparison);
                if (found) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
    
       
//    protected final int compare(Object x, Object y) {
//        return ((Comparable)x).compareTo(y);
//    }
   
//    private boolean contains(Object element, ArrayList myList) {
//        boolean result = false;
//        if (!myList.isEmpty()) {
//            for (int j = 0; j < myList.size(); j++) {
//                Object listObj = myList.get(j);
//                int cmp = -1;
//                if (element instanceof techlist)
//                   cmp = compare((techlist)element, (techlist)listObj);
//                else if (element instanceof finalist)
//                    cmp = compare((finalist)element, (finalist)listObj);
//                    
//                if (cmp == 0) {
//                    result = true;
//                    break;
//                }
//                
//            }
//        }
//        return result;
//    }          
    

    
    public int checkTenderCompleteness() {
        GetSessionVariables();
        int foundTender = 0;

        System.err.print("get in check tender completeness");
        try { 
            org.ellectra.wsviewmytends.ViewMyTendersPortType port = service_1.getViewMyTendersPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wsviewmytends.ViewMyTendersRequest part1 = new org.ellectra.wsviewmytends.ViewMyTendersRequest();
            part1.setActorSignature(dUserloginsignature);
            //System.err.print("signature: " + getDUserloginsignature());
            System.err.print("called view my tenders");
            
            org.ellectra.wsviewmytends.ViewMyTendersResponse result = port.viewMyTendersOperation(part1);
            
            renderDeleteText = false;
            btnUploadTechDisabled = "false";
            btnUploadFinadisabled = "false";
            if (result.isReturn()) {
                List<org.ellectra.wsviewmytends.MyTenderType> bpelout = result.getMyTenderDetails();
                //System.err.print("users are : "+bpelout.size());
                for (int i = 0; i < bpelout.size(); i++) {
                    System.err.print("get in for loop");
                    org.ellectra.wsviewmytends.MyTenderType bpelitem = new org.ellectra.wsviewmytends.MyTenderType();
                    bpelitem = bpelout.get(i);

                    int callForTendersID = bpelitem.getCallForTenderID();
                    int thisCall = mycallid;
                    //if tender record found for this call
                    if (callForTendersID == thisCall) {
                        boolean tenderCompleted = bpelitem.isTenderStatus();
                        //since Tech and Fina docs must be submitted together, status will be true at any case -- WRONG
                        if (tenderCompleted) {
                           // NOW btnCreateTenderDisabled = "true"; 
                           System.err.print("User has already submitted a proposal. Tech an Fin docs for this call already exist");
                           
                           org.ellectra.wsviewmytends.ProposalType bpeltech = new org.ellectra.wsviewmytends.ProposalType();
                           bpeltech = bpelitem.getTechDetails();
                           
                           techlist techdoc = new techlist();
                           String file = formatFilename(bpeltech.getFilename());
                           techdoc.setFilename(file);
                           techdoc.setId(bpeltech.getDocID());
                           if (bpeltech.getDescription() != null)
                                techdoc.setDescription(bpeltech.getDescription());
                           techdoc.setLanguage(bpeltech.getLanguage());
                           //if (bpelfina.getTimestamp() != null)
                                //techdoc.setTimestamp(bpelfina.getTimestamp());
                           if (!contains(techdoc, tdoc))
                                tdoc.add(techdoc);
                           
                           org.ellectra.wsviewmytends.ProposalType bpelfina = new org.ellectra.wsviewmytends.ProposalType();
                           bpelfina = bpelitem.getFinaDetails();
                           
                           finalist finadoc = new finalist();
                           file = formatFilename(bpelfina.getFilename());
                           finadoc.setFilename(file);
                           finadoc.setId(bpelfina.getDocID());
                           if (bpelfina.getDescription() != null)
                               finadoc.setDescription(bpelfina.getDescription());
                           finadoc.setLanguage(bpelfina.getLanguage());
                           //if (bpelfina.getTimestamp() != null)
                               //techdoc.setTimestamp(bpelfina.getTimestamp());
                           if (!contains(finadoc, fdoc))
                                fdoc.add(finadoc);
                           
                           foundTender = bpelitem.getTenderId();//foundTender = true;
                           renderDeleteText = true;
                           btnUploadTechDisabled = "true";
                           btnUploadFinadisabled = "true";
                        }
                        else {
                            // NOW btnCreateTenderDisabled = "false";
                            boolean foundTech = bpelitem.isFoundTechProposal();
                            boolean foundFin = bpelitem.isFoundFinancProposal();
                            if (foundTech) {
                                System.err.print("User cannot upload Tech doc");
                                org.ellectra.wsviewmytends.ProposalType bpeltech = new org.ellectra.wsviewmytends.ProposalType();
                                bpeltech = bpelitem.getTechDetails();
                                
                                techlist techdoc = new techlist();
                                String file = formatFilename(bpeltech.getFilename());
                                techdoc.setFilename(file);
                                techdoc.setId(bpeltech.getDocID());
                                if (bpeltech.getDescription() != null)
                                    techdoc.setDescription(bpeltech.getDescription());
                                techdoc.setLanguage(bpeltech.getLanguage());
                                //if (bpelfina.getTimestamp() != null)
                                    //techdoc.setTimestamp(bpelfina.getTimestamp());
                                if (!contains(techdoc, tdoc))
                                    tdoc.add(techdoc);
                                
                                //renderDeleteText = true;
                            }
                            if (foundFin) {
                                System.err.print("User cannot upload Fin doc");
                                org.ellectra.wsviewmytends.ProposalType bpelfina = new org.ellectra.wsviewmytends.ProposalType();
                                bpelfina = bpelitem.getFinaDetails();
                                
                                finalist finadoc = new finalist();
                                String file = formatFilename(bpelfina.getFilename());
                                finadoc.setFilename(file);
                                finadoc.setId(bpelfina.getDocID());
                                if (bpelfina.getDescription() != null)
                                    finadoc.setDescription(bpelfina.getDescription());
                                finadoc.setLanguage(bpelfina.getLanguage());
                                //if (bpelfina.getTimestamp() != null)
                                    //techdoc.setTimestamp(bpelfina.getTimestamp());
                                if (!contains(finadoc, fdoc))
                                    fdoc.add(finadoc);
                                
                                //renderDeleteText = true;
                            }
                            foundTender = bpelitem.getTenderId();//foundTender = true;
                        }
                       //btnCreateTenderDisabled = "true"; 
                       System.err.print("get in join to call");
                       break;
                    }//join to call
                    
                }//for
            }
            else {
               //NOW btnCreateTenderDisabled = "false";
               System.err.print("there is no tender generally (i.e. for any call) submitted by this user"); 
               //foundTender = false;
               renderDeleteText = false;
            }
            
            //System.out.println("Result = " + result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            ex.printStackTrace();
        }
        return foundTender;
    }

    
    /**
     * Function used to create record in the table of tenders
     * Such record is created only if it does not exist.
     * @return
     */
    public String CreateTender() {
        //searchresultlist Selected= (searchresultlist) this.getSresdata().getRowData();
        //ictenderselected=Selected.getSrid();
        //JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID", Integer.toString(ictenderselected));      
        int tenderExist = checkTenderCompleteness();
        if (tenderExist == 0) {
        
            try {
                org.ellectra.wsst.SubmissionOfTenderPortType port = service.getSubmissionOfTenderPort();

                org.ellectra.wsst.Request request = new org.ellectra.wsst.Request();
                request.setAction("SUBMITTENDER");
                request.setCallid(mycallid);
                request.setDoctype("0");

                String dUserloginid = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINUSERID");
                request.setUserid(Integer.valueOf(dUserloginid));
                request.setDescription("NA");
                request.setFile("NA");
                request.setLanguage("NA");
                request.setOrganization("NA");
                request.setPath("NA");
                request.setRole("NA");
                request.setSignature("NA");
                request.setTenderid("NA");
                request.setTenderidint(0);
                request.setUsername("NA");

                org.ellectra.wsst.Response result = port.submissionOfTenderOperation(request);

                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERIDI", result.getId());
                //setRenderDeleteText(false);
                System.err.println("CREATE RECORD: TENDER");
                return "starttender";

            } catch (Exception ex) {
                return "error";
            }
        }// create a new record only if tender does not already exist
        else {
            //setRenderDeleteText(true);
            //fill in tech and fina lists from bpel
            //private ArrayList<techlist> tdoc = new ArrayList();
            //private ArrayList<finalist> fdoc = new ArrayList();
            //OK
            System.err.println("NOT CREATE RECORD: TENDER");
            System.err.println("TENDER ID is: " + Integer.toString(tenderExist));
            JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERIDI", Integer.toString(tenderExist));
            return "starttender";
        }
            
    }

   
    
    // Getters ------------------------------------------------------------------------------------
    public String getBtnSubmitDisabled() {
        System.err.println("---- getBtnSubmitDisabled -----");
        System.err.println("tdata rowcounter: " + tdata.getRowCount());
        System.err.println("fdata rowcounter: " + fdata.getRowCount());
        if ((tdata.getRowCount() > 0) && (fdata.getRowCount() > 0))
            btnSubmitDisabled = "false";
        else
            btnSubmitDisabled = "true";
        
        return btnSubmitDisabled;
    }

    public void setBtnSubmitDisabled(String btnSubmitDisabled) {
        this.btnSubmitDisabled = btnSubmitDisabled;
    }
    
    public String getBtnUploadTechDisabled() {
//        System.err.println("---- getBtnUpload tech Disabled -----");
//        System.err.println("tdata rowcounter: " + tdata.getRowCount());
//        if (tdata.getRowCount() > 0) 
//            btnUploadTechDisabled = "true";
//        else
//            btnUploadTechDisabled = "false";
        
        return btnUploadTechDisabled;
    }

    public void setBtnUploadTechDisabled(String btnUploadTechDisabled) {
        this.btnUploadTechDisabled = btnUploadTechDisabled;
    }

    public String getBtnUploadFinadisabled() {
//        System.err.println("---- getBtnUpload fina Disabled -----");
//        System.err.println("fdata rowcounter: " + fdata.getRowCount());
//        if (fdata.getRowCount() > 0)
//            btnUploadFinadisabled = "true";
//        else
//            btnUploadFinadisabled = "false";
        
        return btnUploadFinadisabled;
    }

    public void setBtnUploadFinadisabled(String btnUploadFinadisabled) {
        this.btnUploadFinadisabled = btnUploadFinadisabled;
    }

    public boolean isRenderDeleteText() {
        //if ((tdata.getRowCount() == 0) && (fdata.getRowCount() == 0))
            //renderDeleteText = false;
        
        return renderDeleteText;
    }

    public void setRenderDeleteText(boolean renderDeleteText) {
        this.renderDeleteText = renderDeleteText;
    }

    
    
    
    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public String getFileName() {
        return fileName;
    }

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

    public ArrayList<prooflist> getPdoc() {
        return pdoc;
    }

    public void setPdoc(ArrayList<prooflist> pdoc) {
        this.pdoc = pdoc;
    }

    public ArrayList<techlist> getTdoc() {
        return tdoc;
    }

    public void setTdoc(ArrayList<techlist> tdoc) {
        this.tdoc = tdoc;
    }

    public ArrayList<finalist> getFdoc() {
        return fdoc;
    }

    public void setFdoc(ArrayList<finalist> fdoc) {
        this.fdoc = fdoc;
    }

    public UIData getPdata() {
        return pdata;
    }

    public void setPdata(UIData pdata) {
        this.pdata = pdata;
    }

    public UIData getTdata() {
        return tdata;
    }

    public void setTdata(UIData tdata) {
        this.tdata = tdata;
    }

    public UIData getFdata() {
        return fdata;
    }

    public void setFdata(UIData fdata) {
        this.fdata = fdata;
    }

    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 ArrayList<techlist> getRemovedTechIDs() {
        return removedTechIDs;
    }

    public void setRemovedTechIDs(ArrayList<techlist> removedTechIDs) {
        this.removedTechIDs = removedTechIDs;
    }

    public ArrayList<finalist> getRemovedFinaIDs() {
        return removedFinaIDs;
    }

    public void setRemovedFinaIDs(ArrayList<finalist> removedFinaIDs) {
        this.removedFinaIDs = removedFinaIDs;
    }



    
    
}
