package org.ellectra.gui.managebeans;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceRef;
import org.ellectra.calculatescores.CalculateScoreService;
import org.ellectra.closeevaluation.CloseEvaluationService;
import org.ellectra.gui.utils.JSFUtils;
import org.ellectra.tendersinfo.GetTendersInfoService;
import org.ellectra.wsevaluation.EvaluateTenderService;
import org.ellectra.wsrejecttender.RejectTenderService;
import org.ellectra.wstechvalues.AwardEvaluationType;
import org.ellectra.wstechvalues.ManageAwardValuesService;

public class evaluatefinadoc {
    @WebServiceRef(wsdlLocation = "http://localhost:18181/GetTendersInfoService/GetTendersInfoPort?wsdl")
    private GetTendersInfoService service_5;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/CalculateScoreService/CalculateScorePort?wsdl")
    private CalculateScoreService service_4;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/ManageAwardValuesService/ManageAwardValuesPort?wsdl")
    private ManageAwardValuesService service;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/RejectTenderService/RejectTenderPort?wsdl")
    private RejectTenderService service_3;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/CloseEvaluationService/CloseEvaluationPort?wsdl")
    private CloseEvaluationService service_2;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/EvaluateTenderService/EvaluateTenderPort?wsdl")
    private EvaluateTenderService service_1;
    String tendername;
    String c1score;
    String c2score;
    String c3score;
    String c1just;
    String c2just;
    String c3just;
    String c1name;
    String c2name;
    String c3name;
    String reject;
    String dUserloginname;
    String dUserloginsignature;
    String dUserloginOrganization;
    String dUserloginrole;
    int dUserloginid;
    int mytenderid;
    int mycalloftender;
    private UIData finaData = null;
    private ArrayList<evaluationlist> finaCriteria = new ArrayList();
    
    private String thisTenderer;
    private UIData fdata = null;
    private ArrayList<finalist> fdoc = new ArrayList();
    String szPath;
    String szPathb;
    
   public evaluatefinadoc() {
        super();
        pathSettings dset = new pathSettings();
        szPath = dset.GetUploadDirectory();
        szPathb = dset.GetUploadbDirectory();
    }

    public String getReject() {
        return reject;
    }

    public void setReject(String reject) {
        this.reject = reject;
    }

    public String getTendername() {
        return tendername;
    }

    public void setTendername(String tendername) {
        this.tendername = tendername;
    }

    public String getC1score() {
        return c1score;
    }

    public void setC1score(String c1score) {
        this.c1score = c1score;
    }

    public String getC2score() {
        return c2score;
    }

    public void setC2score(String c2score) {
        this.c2score = c2score;
    }

    public String getC3score() {
        return c3score;
    }

    public void setC3score(String c3score) {
        this.c3score = c3score;
    }

    public String getC1just() {
        return c1just;
    }

    public void setC1just(String c1just) {
        this.c1just = c1just;
    }

    public String getC2just() {
        return c2just;
    }

    public void setC2just(String c2just) {
        this.c2just = c2just;
    }

    public String getC3just() {
        return c3just;
    }

    public void setC3just(String c3just) {
        this.c3just = c3just;
    }

    public String getC1name() {
        return c1name;
    }

    public void setC1name(String c1name) {
        this.c1name = c1name;
    }

    public String getC2name() {
        return c2name;
    }

    public void setC2name(String c2name) {
        this.c2name = c2name;
    }

    public String getC3name() {
        return c3name;
    }

    public void setC3name(String c3name) {
        this.c3name = c3name;
    }

    public String formatFilename(String filepath){
        int lastSlash = filepath.lastIndexOf("/");
        return filepath.substring(lastSlash + 1, filepath.length());
    }
    
    public String getTenderFileMetadata() {
        String dValue = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ddddevaluatetenderidfina");
        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERIDI", dValue);
        
        String mappedTenderOrgValue = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("tenderOrg");
        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERORG", mappedTenderOrgValue);
        
        fdoc.clear();
        GetSessionVariables();

        try { // Call Web Service Operation
            org.ellectra.tendersinfo.GetTendersInfoPortType port = service_5.getGetTendersInfoPort();
            // TODO initialize WS operation arguments here
            org.ellectra.tendersinfo.GetTendersInfoRequest part1 = new org.ellectra.tendersinfo.GetTendersInfoRequest();
            part1.setActorSignature(dUserloginsignature);
            part1.setTenderId(mytenderid);

            // TODO process result here
            org.ellectra.tendersinfo.GetTendersInfoResponse result = port.getTendersInfoOperation(part1);
            List<org.ellectra.tendersinfo.ProposalType> bpelout = result.getFinaDetails();

            System.err.print("found file metadata for this tender");
            for (int i = 0; i < bpelout.size(); i++) {
                System.err.print("get in for loop");
                org.ellectra.tendersinfo.ProposalType bpelitem = new org.ellectra.tendersinfo.ProposalType();
                bpelitem = bpelout.get(i);

                finalist finadoc = new finalist();
                String file = formatFilename(bpelitem.getFilename());
                finadoc.setFilename(file);
                finadoc.setId(bpelitem.getDocID());
                if (bpelitem.getDescription() != null) {
                    finadoc.setDescription(bpelitem.getDescription());
                }
                String DATE_FORMAT2 = "dd-MM-yyyy HH:mm:ss";
                DateFormat sdf2 = new SimpleDateFormat(DATE_FORMAT2);
                GregorianCalendar dateReceived = null;
                String formattedDate = "";
                if (bpelitem.getTimestamp() != null) {
                    dateReceived = bpelitem.getTimestamp().toGregorianCalendar();
                    //sdf3.setTimeZone(TimeZone.getDefault());
                    formattedDate = sdf2.format(dateReceived.getTime());
                    finadoc.setTimestamp(formattedDate);
                }
                
                fdoc.add(finadoc);
               
            }//for
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
        return "viewFinaDocs";
    }
    
    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");
        String szTemp = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINUSERID");
        dUserloginid = Integer.valueOf(szTemp).intValue();
        szTemp = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "TENDERIDI");
        mytenderid = Integer.valueOf(szTemp).intValue();
        szTemp = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID");
        mycalloftender = Integer.valueOf(szTemp).intValue();
    //callForTender Title
    //Tenderer

    }

    public void populateListddd() {
        GetSessionVariables();
        finaCriteria.clear();

        try { // Call Web Service Operation

            org.ellectra.wstechvalues.ManageAwardValuesPortType port = service.getManageAwardValuesPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wstechvalues.ManageAwardValuesRequest part1 = new org.ellectra.wstechvalues.ManageAwardValuesRequest();
            part1.setAction("FR20_AwValues_Read");
            part1.setActorSignature("[B@6248a0");
            part1.setCallForTenderID(902);
            part1.setTenderID(930);
            part1.setCriterionType("FINANCIAL");
            // TODO process result here
            org.ellectra.wstechvalues.ManageAwardValuesResponse result = port.manageAwardValuesOperation(part1);
            System.out.println("Result = " + result);
            List<org.ellectra.wstechvalues.AwardEvaluationType> ddd = result.getAwardCriterion();
            System.out.println("size " + ddd.size());
            org.ellectra.wstechvalues.AwardEvaluationType ditem = new org.ellectra.wstechvalues.AwardEvaluationType();
            ditem = ddd.get(0);
            if (ditem.getCriterionType() != null) {
                System.out.println("type " + ditem.getCriterionType());
            }
            ditem = ddd.get(1);
            if (ditem.getCriterionType() != null) {
                System.out.println("type " + ditem.getCriterionType());
            }
            ditem = ddd.get(2);
            if (ditem.getCriterionType() != null) {
                System.out.println("type " + ditem.getCriterionType());
            }
            ditem = ddd.get(3);
            if (ditem.getCriterionType() != null) {
                System.out.println("type " + ditem.getCriterionType());
            }
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.out.println("type error");
        }

    }

    public void populateList() {
        GetSessionVariables();
        finaCriteria.clear();
        
        try { // Call Web Service Operation

            org.ellectra.wstechvalues.ManageAwardValuesPortType port = service.getManageAwardValuesPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wstechvalues.ManageAwardValuesRequest part1 = new org.ellectra.wstechvalues.ManageAwardValuesRequest();
            part1.setAction("FR20_AwValues_Read");
            part1.setActorSignature(dUserloginsignature);
            part1.setCallForTenderID(mycalloftender);
            part1.setTenderID(mytenderid);
            part1.setCriterionType("FINANCIAL");

//            // TODO process result here
            org.ellectra.wstechvalues.ManageAwardValuesResponse result = port.manageAwardValuesOperation(part1);
            List<org.ellectra.wstechvalues.AwardEvaluationType> ddd = result.getAwardCriterion();
//
            System.out.println("size " + ddd.size());
            for (int t = 0; t < ddd.size(); t++) {
                org.ellectra.wstechvalues.AwardEvaluationType ditem = new org.ellectra.wstechvalues.AwardEvaluationType();
                ditem = ddd.get(t);
                System.out.println("type " + ditem.getCriterionType());
                if (ditem.getCriterionType() != null) {
                    evaluationlist dd1 = new evaluationlist();
                    dd1.setCreditio(ditem.getCriterion());
                    System.out.println("criterion " + ditem.getCriterion());
                    dd1.setId(ditem.getAwardID());
                    System.out.println("awaID " + ditem.getAwardID());
                    dd1.setNumber(String.valueOf(ditem.getAwardID()));


                    if (result.isValuesExist()) {
                        System.out.println("valuesexist");
                        //Double temp = new Double(ditem.getScore());
                        //dd1.setScore(String.valueOf(temp.intValue()));
                        //dd1.setScore(String.valueOf(ditem.getScore().intValue()));
                        
                        dd1.setScore(Double.toString(ditem.getScore()));
                        System.out.println("score " + dd1.getScore());
                        dd1.setValueid(ditem.getAwardValueID());
                        if (ditem.getJustification() != null) {
                            dd1.setJustification(ditem.getJustification());
                        }
                    } else {
                        dd1.setScore("0");
                    }
                    finaCriteria.add(dd1);

                }
            }

            System.out.println("Result = " + result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }

    }

    public String Evaluatefinadocsfortender() {
        String dValue = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ddddevaluatetenderidfina");
        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERIDI", dValue);
        
        String mappedTenderOrgValue = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("tenderOrg");
        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERORG", mappedTenderOrgValue);
        
        populateList();
        return "gotofina";
    }

   public String getThisTenderer() {
        String currentTenderer = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "TENDERORG");
        thisTenderer = currentTenderer;
        
        return thisTenderer;
    }

    public void setThisTenderer(String thisTenderer) {
        this.thisTenderer = thisTenderer;
    }
    
    public String performEvaluation() {
        GetSessionVariables();
        
        try { // Call Web Service Operation

            org.ellectra.wsevaluation.EvaluateTenderPortType port = service_1.getEvaluateTenderPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wsevaluation.EvaluateTenderRequest part1 = new org.ellectra.wsevaluation.EvaluateTenderRequest();
            part1.setAction("notused");
            part1.setActorSignature(dUserloginsignature);
            part1.setCallForTenderID(mycalloftender);
            part1.setTenderID(mytenderid);
            part1.setEvaluationPhase("PHASE_III");
            List<org.ellectra.wsevaluation.AwardEvaluationType> dlocalist = part1.getFinCriterion();
            for (int i = 0; i < finaCriteria.size(); i++) {
                evaluationlist ditem = finaCriteria.get(i);
                org.ellectra.wsevaluation.AwardEvaluationType bpelin = new org.ellectra.wsevaluation.AwardEvaluationType();
                bpelin.setAwardID(ditem.getId());
                String valueid = String.valueOf(ditem.getValueid());
                if (valueid != null) {
                    System.out.println("EV 7 save not null");
                    bpelin.setAwardValueID(ditem.getValueid());
                //if (ditem.getScore().equals("0"))
                //WHAT?????;
                }
                if (ditem.getJustification() != null) {
                    bpelin.setJustification(ditem.getJustification());
                }
                bpelin.setScore(Double.parseDouble(ditem.getScore()));
                dlocalist.add(bpelin);
                
            }

            // TODO process result here
            org.ellectra.wsevaluation.EvaluateTenderResponse result = port.evaluateTenderOperation(part1);
            System.out.println("Result = " + result.getReturnMessage());
        } catch (Exception ex) {
            System.out.println("error" + ex.getLocalizedMessage());
        // TODO handle custom exceptions here
        }

        return "ok";
    }

    public String closeEvaluation() {
        GetSessionVariables();

        String returnto = "";
        try { // Call Web Service Operation

            org.ellectra.closeevaluation.CloseEvaluationPortType port = service_2.getCloseEvaluationPort();
            // TODO initialize WS operation arguments here
            org.ellectra.closeevaluation.CloseEvaluationRequest part1 = new org.ellectra.closeevaluation.CloseEvaluationRequest();
            part1.setActorSignature(dUserloginsignature);//notUsed
            part1.setCallForTenderID(mycalloftender);//notUsed
            part1.setPhaseToClose("PHASE_III");

            // TODO process result here
            org.ellectra.closeevaluation.CloseEvaluationResponse result = port.closeEvaluationOperation(part1);
            if (result.isReturn()) {
                String calculationResult = calculateScores();
                if (calculationResult.equals("success"))
                    returnto = "viewranking";
                else
                    returnto = "samepage";
            } else {
                returnto = "samepage";
            }
            System.out.println("Result = " + result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here //ok
        }
        return returnto;
    }

    public String rejectTender() {
        GetSessionVariables();
        String returnto = "";
        performEvaluation();

        try { // Call Web Service Operation

            org.ellectra.wsrejecttender.RejectTenderPortType port = service_3.getRejectTenderPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wsrejecttender.RejectTenderRequest part1 = new org.ellectra.wsrejecttender.RejectTenderRequest();
            part1.setActorSignature(dUserloginsignature);
            part1.setCallForTenderID(mycalloftender);
            part1.setTenderID(mytenderid);
            part1.setPhase("PHASE_III");
            part1.setRejectedJustication(getReject());


            // TODO process result here
            org.ellectra.wsrejecttender.RejectTenderResponse result = port.rejectTenderOperation(part1);
            if (result.isReturn()) {
                returnto = "ok";
            } else {
                returnto = "samepage";
            }
            System.out.println("Result = " + result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
        return returnto;
    }

    public String calculateScores() {
        GetSessionVariables();
        String resultIs = "failure";

        try { // Call Web Service Operation

            org.ellectra.calculatescores.CalculateScorePortType port = service_4.getCalculateScorePort();
            // TODO initialize WS operation arguments here
            org.ellectra.calculatescores.CalculateScoreRequest part1 = new org.ellectra.calculatescores.CalculateScoreRequest();
            part1.setActorSignature(dUserloginsignature);
            part1.setCallForTenderID(mycalloftender);
            
            org.ellectra.calculatescores.CalculateScoreResponse result = port.calculateScoreOperation(part1);
            if (result.isReturn()) {
                resultIs = "success";
            } else {
                resultIs = "failure";
            }
            
            System.out.println("Result = " + result);
        } catch (Exception ex) {
            // TODO handle custom exceptions here  
            ex.printStackTrace();
        }
        return resultIs;
    }
    
   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 = szPathb + 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 UIData getFinaData() {
        return finaData;
    }

    public void setFinaData(UIData finaData) {
        this.finaData = finaData;
    }

    public ArrayList<evaluationlist> getFinaCriteria() {
        return finaCriteria;
    }

    public void setFinaCriteria(ArrayList<evaluationlist> finaCriteria) {
        this.finaCriteria = finaCriteria;
    }
    
    public UIData getFdata() {
        return fdata;
    }

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

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

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