package org.ellectra.gui.managebeans;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.ValidatorException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;
import org.ellectra.gui.utils.JSFUtils;
import org.ellectra.wscall.ManageWorkspaceService;

public class createtenderworkspace {

    @WebServiceRef(wsdlLocation = "http://localhost:18181/ManageWorkspaceService/ManageWorkspacePort?WSDL")
    private ManageWorkspaceService service;
    
    private String title;
    private String contractType;
    private String nuts = "   ";
    private String cpv;//="  ";
    private String voc = "  ";
    private String[] noticeInvolves;
    private String description;
    
    private Double estimatedValue;
    private String currency;
    private Integer durationInMonths;
    private Integer durationInDays;
    
    private Date contractStarts;
    private Date contractEnds;
    private String contractDuration = "1";
    
    private String procedureType;
    private String a_ctw16;// = " ";
    private String a_ctw17;// = " ";
    private String a_ctw18;// = " ";
    private Date a_ctw19;// = new Date();
    private String a_ctw20;// = " ";
    private String a_ctw21;// = " ";
    private String a_ctw22;// = " ";
    private Date a_ctw23;// = new Date();
    
    private String a_ctw24;
    private String a_ctw25;
    private String a_ctw26;
    
    private Date dateCNdispatch;
    private String openDate = " ";
    private String closeDate = " ";
    private Integer numOfDays;
    private String ecntransmission;
    private String econtractDocs;
    
    private String errorMessage;
    private boolean connectionError;
    private boolean numbercd = true;
    private boolean datecd = false;

    public createtenderworkspace() {
        super();
        ecntransmission = "yes";
        econtractDocs = "yes";
    }

    private void reset() {
        nuts = "   ";        
        //cpv="  ";
        //cpv = "";
        voc = "  ";
        
        contractDuration = "1";
        numbercd = true;
        datecd = false;
        
        //////////////////clear them - check with null////////////
        title = "";
        //String[] noticeInvolves;
        description = "";
        //Double estimatedValue;
        //Integer durationInMonths;
        //Integer durationInDays;
        //Date contractStarts;
        //Date contractEnds;
        //DO WE NEED THIS - String contractDuration = "1";

        a_ctw16 = "";
        a_ctw17 = "";
        a_ctw18 = "";
        //Date a_ctw19;// = new Date();
        a_ctw20 = "";
        a_ctw21 = "";
        a_ctw22 = "";
        //Date a_ctw23;// = new Date();

        //Date dateCNdispatch;
        openDate = " ";
        closeDate = " ";
        //Integer numOfDays;
        
    }

    public String cancel() {

        return "cancel";
    }

    private String GetUserSignatureFromSession() {
        String dtemp = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINSIGNATURE");
        return dtemp;
    }

    private XMLGregorianCalendar ConvertDateToXML(Date date) {

        try {
            String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);

            SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);


            pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
            pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);


            GregorianCalendar gc = new GregorianCalendar(pdt);
            gc.setTime(date);

            XMLGregorianCalendar xmlCaltemp = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
            return xmlCaltemp;
            
        } catch (DatatypeConfigurationException ex) {
            return null;
        }
    }

    private Date ConvertToDate(String dateStr) {
        try {
            String mydatestring = dateStr;
            String DATE_FORMAT = "dd/MM/yyyy";
            
            Date dt = new SimpleDateFormat(DATE_FORMAT).parse(mydatestring);
            return dt;
            
        } catch (ParseException ex) {
            return new Date();
        }
    }

    /**
     * Create a tenders workspace
     * @return
     */
    public String createWorkspace() {
        System.err.println("get in create....");
        
        try { 
            org.ellectra.wscall.ManageWorkspacePortType port = service.getManageWorkspacePort();

            org.ellectra.wscall.ManageWorkspaceRequest part1 = new org.ellectra.wscall.ManageWorkspaceRequest();
            part1.setAction("FR5_Workspace_Create");
            part1.setActorSignature(GetUserSignatureFromSession());

            
            //Set the Internal Reference Number comply to pattern: "currentYear / thisCallID"
            //GregorianCalendar gc = new GregorianCalendar();
            //String currentYear = String.valueOf(gc.get(GregorianCalendar.YEAR));
            //setInternalRefNum(currentYear + " / " + result.getCallForTendersID());
            //SOS: call id not exists right now
            part1.setInternalReferenceNumber("NA");
            
            
            part1.setTitle(getTitle());
            part1.setContractType(getContractType().toUpperCase());
            part1.setDescription(getDescription());
            part1.setCurrency(getCurrency());
            part1.setProcedureType(getProcedureType());
            
            
            part1.setNoticeInvolvesPC(false);
            part1.setNoticeInvolvesDPS(false);
            part1.setNoticeInvolvesFA(false);
            for (int i = 0; i < noticeInvolves.length; i++) {
                if (noticeInvolves[i].equals("pc")) {
                    part1.setNoticeInvolvesPC(true);
                }
                if (noticeInvolves[i].equals("dps")) {
                    part1.setNoticeInvolvesDPS(true);
                }
                if (noticeInvolves[i].equals("fa")) {
                    part1.setNoticeInvolvesFA(true);
                }
            }
            
            if (estimatedValue != null)
                part1.setEstimatedValue(estimatedValue);
            
            if (durationInMonths != null)
                part1.setDurationInMonths(durationInMonths);
            
            if (durationInDays != null)
                part1.setDurationInDays(durationInDays);
            
            if (contractStarts != null)
                part1.setContractStarts(ConvertDateToXML(contractStarts));
            
            if (contractEnds != null)
                part1.setContractEnds(ConvertDateToXML(contractEnds));    

            if (getEcntransmission().equals("yes"))
                part1.setETransmissionOfCN(true);
            else
                part1.setETransmissionOfCN(false);
            
            
            if (getEcontractDocs().equals("yes"))
                part1.setEContractDocs(true);
            else
                part1.setEContractDocs(false);            
            
            
            if (getDateCNdispatch() != null)
                part1.setCNsubmissionDate(ConvertDateToXML(dateCNdispatch));

            if (getOpenDate().length() > 2) {
                Date openDate = ConvertToDate(getOpenDate());
                part1.setOpenCallDate(ConvertDateToXML(openDate));
            }

            if (getCloseDate().length() > 2) {
                Date closeDate = ConvertToDate(getCloseDate());
                part1.setCloseCallDate(ConvertDateToXML(closeDate));
            }
            else
            part1.setCloseCallDate(ConvertDateToXML(new Date()));
            
            if (numOfDays != null) 
                part1.setOpenTendersAfterClosingDate(numOfDays);
           
            
            ///////////////////////////////////////////////////////////
            part1.setCPV(cpv);
            part1.setVOC(voc);
            part1.setNUTS(nuts);

            
            String regExpA = "\\d{4}"; 
            String regExpB = "\\d{3}";
            String regExpC = "\\d{6}";
                
            if (getA_ctw16() != null && getA_ctw17() != null && getA_ctw18() != null && getA_ctw19() != null) {
                if (Pattern.matches(regExpA, getA_ctw16()) && Pattern.matches(regExpB, getA_ctw17()) && Pattern.matches(regExpC, getA_ctw18())) {
                    part1.setPINcode(getA_ctw16() + "/S " + getA_ctw17() + "-" + getA_ctw18());
                    part1.setPINsubmitted(ConvertDateToXML(getA_ctw19()));
                }
            }
            //else
                //part1.setPINcode("NA");
           
            if (getA_ctw20() != null && getA_ctw21() != null && getA_ctw22() != null && getA_ctw23() != null) {
                if (Pattern.matches(regExpA, getA_ctw20()) && Pattern.matches(regExpB, getA_ctw21()) && Pattern.matches(regExpC, getA_ctw22())) {
                    part1.setOtherPINcode(getA_ctw20() + "/S " + getA_ctw21() + "-" + getA_ctw22());
                    part1.setOtherPINsubmitted(ConvertDateToXML(getA_ctw23()));
                }
            }
            //else
                //part1.setOtherPINcode("NA");
           

            //we will initialize this values later
            part1.setDirectoryName("Call");
        
            pathSettings dset=new pathSettings();
            String szPathdb=dset.GetUploadDirectory();
   
            part1.setDirectoryPath(szPathdb);
            //  part1.setOjeuReferenceNumber("NA");
            
            org.ellectra.wscall.ManageWorkspaceResponse result = port.manageWorkspaceOperation(part1);
            if (result.isReturn()) {
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID", Integer.toString(result.getCallForTendersID()));
                reset();
                System.out.println("Result = " + result.getCallForTendersID());
                return "showctviewpoa";
            } else {
                setErrorMessage(result.getReturnMessage());
                setConnectionError(false);
                reset();
                return "failure";
            }


        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.err.println("EXCEPTION WHILE CREATING CALL WORKSPACE");
            ex.printStackTrace();
            setConnectionError(true);
            reset();
            return "failure";
        }


    }
    
    public void validatePartA (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
            String partA = (String)value;
            String regExpA = "\\d{4}"; 
            if (!Pattern.matches(regExpA, partA)) {
                    FacesMessage message = new FacesMessage("Code's first field doesn't match the pattern DDDD");
                    context.addMessage("createtenderworkspace", message);
                    throw new ValidatorException(message);
            }
    }
    
    public void validatePartB (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
            String partB = (String)value;
            String regExpB = "\\d{3}"; 
            if (!Pattern.matches(regExpB, partB)) {
                    FacesMessage message = new FacesMessage("Code's second field doesn't match the pattern DDD");
                    context.addMessage("createtenderworkspace", message);
                    throw new ValidatorException(message);
            }
    }
    
    public void validatePartC (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
            String partC = (String)value;
            String regExpC = "\\d{6}"; 
            if (!Pattern.matches(regExpC, partC)) {
                    FacesMessage message = new FacesMessage("Code's third field doesn't match the pattern DDDDDD");
                    context.addMessage("createtenderworkspace", message);
                    throw new ValidatorException(message);
            }
    }

/*    public void calculate() {
        
        System.err.println("Date CNget: " + getDateCNdispatch());

        String mydatestring = getDateCNdispatch().toString();
        
        Date dt;
        String DATE_FORMAT = "MM/dd/yyyy";
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
        Calendar c1 = Calendar.getInstance();
        try {
            dt = sdf.parse(mydatestring);
            c1.setTime(dt);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block , Do we need this ??
            e1.printStackTrace();
        }

        c1.add(Calendar.DATE, 5);

        setOpenDate(sdf.format(c1.getTime()));


        c1.add(Calendar.DATE, 52);
        if (getEcntransmission().equalsIgnoreCase("yes")) {
            c1.add(Calendar.DATE, -7);
        }
        if (getEcontractDocs().equalsIgnoreCase("yes")) {
            c1.add(Calendar.DATE, -5);
        }
        setCloseDate(sdf.format(c1.getTime()));
        
        //FacesContext context = FacesContext.getCurrentInstance();
        //context.renderResponse();
        
    }*/

    
    public void calculate() {
        
        if (getDateCNdispatch() != null) {
            Date cnDate = getDateCNdispatch();
            Calendar c = Calendar.getInstance();
            c.setTime(cnDate);

            String DATE_FORMAT = "dd/MM/yyyy";
            DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);

            c.add(Calendar.DATE, 5);
            System.out.println("OPEN CALL: " + sdf.format(c.getTime()));
            setOpenDate(sdf.format(c.getTime()));


            c.add(Calendar.DATE, 52);
            if (getEcntransmission().equalsIgnoreCase("yes")) {
                c.add(Calendar.DATE, -7);
            }
            if (getEcontractDocs().equalsIgnoreCase("yes")) {
                c.add(Calendar.DATE, -5);
            }

            System.out.println("CLOSE CALL: " + sdf.format(c.getTime()));
            setCloseDate(sdf.format(c.getTime()));
        }
    }
        

    public void eventStartDate(ValueChangeEvent vce) {
            contractStarts = (Date) vce.getNewValue();
    }

    public void eventEndDate(ValueChangeEvent vce) {
            contractEnds = (Date) vce.getNewValue();
    }
    
//    public void validateStart(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
//        System.err.println("get in Start date validator");
//        
//        Date startDate = (Date) value;
//        Date endDate = getContractEnds();
//        if (endDate != null) {
//            if (endDate.before(startDate) || endDate.equals(startDate)) {
//                FacesMessage message = new FacesMessage("Contract start date must be before contract end date");
//                context.addMessage("createtenderworkspace", message);
//                throw new ValidatorException(message);
//            }
//        }
//    }
    
//    public void validateEnd(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
//        System.err.println("get in End date validator");
//        
//        Date endDate = (Date) value;
//        Date startDate = getContractStarts();
//        if (startDate != null) {
//            if (startDate.after(endDate) || startDate.equals(endDate)) {
//                FacesMessage message = new FacesMessage("Contract start date must be before contract end date");
//                context.addMessage("createtenderworkspace", message);
//                throw new ValidatorException(message);
//            }
//        }
//    }
    


//    public void validateCPV(FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
//        String cpvCode = (String) value;
//        System.err.println("cpv length: " + cpvCode.length());
//        if (cpvCode.length() < 3) {
//            FacesMessage message = new FacesMessage("CPV code(s) for main object(s) is an obligatory field");
//            context.addMessage("createtenderworkspace", message);
//            throw new ValidatorException(message);
//        }
//    }
    
    public Date getContractStarts() {
        System.err.println("START: " + contractStarts);
        return contractStarts;
    }

    public void setContractStarts(Date contractStarts) {
        this.contractStarts = contractStarts;
    }

    public Date getContractEnds() {
        System.err.println("END: " + contractEnds);
        return contractEnds;
    }

    public void setContractEnds(Date contractEnds) {
        this.contractEnds = contractEnds;
    }
    
    public Date getDateCNdispatch() {
        return dateCNdispatch;
    }

    public void setDateCNdispatch(Date dateCNdispatch) {
        this.dateCNdispatch = dateCNdispatch;
    }

    public String getOpenDate() {
        System.err.println("OPEN STR: " + openDate);
        return openDate;
    }

    public void setOpenDate(String openDate) {
        this.openDate = openDate;
    }

    public String getCloseDate() {
        System.err.println("CLOSE STR: " + closeDate);
        return closeDate;
    }

    public void setCloseDate(String closeDate) {
        this.closeDate = closeDate;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContractType() {
        return contractType;
    }

    public void setContractType(String contractType) {
        this.contractType = contractType;
    }

    public String getNuts() {
        java.lang.String nutsmaincode = (java.lang.String) org.ellectra.gui.utils.JSFUtils.retrieveOnSession(javax.faces.context.FacesContext.getCurrentInstance(), "NUTSFORCREATETENDER");
        nuts = nutsmaincode;
        return nuts;
    }

    public void setNuts(String nuts) {
        this.nuts = nuts;
    }

    public String[] getNoticeInvolves() {
        return noticeInvolves;
    }

    public void setNoticeInvolves(String[] noticeInvolves) {
        this.noticeInvolves = noticeInvolves;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
    


    public String getCpv() {
        java.lang.String cpvmaincode = (java.lang.String) org.ellectra.gui.utils.JSFUtils.retrieveOnSession(javax.faces.context.FacesContext.getCurrentInstance(), "MAINCPVFORCREATETENDER");
        // use variables session here
        cpv = cpvmaincode;
        System.err.println("cpv length: " + cpv.length());
        System.err.println("CPV code session value: [" + cpv + "]");
        //if (cpv.length() < 3) {
            //errorMessage = "CPV code(s) for main object(s) is an obligatory field";
        //}
        
        return cpv;
    }

    public void setCpv(String cpv) {
        // use variables session here
        this.cpv = cpv;
    }

    public String getVoc() {
        java.lang.String cpvmaincode = (java.lang.String) org.ellectra.gui.utils.JSFUtils.retrieveOnSession(javax.faces.context.FacesContext.getCurrentInstance(), "VOCFORCREATETENDER");
        // use variables session here
        voc = cpvmaincode;

        return voc;
    }

    public void setVoc(String voc) {
        this.voc = voc;
    }

    public Double getEstimatedValue() {
        return estimatedValue;
    }

    public void setEstimatedValue(Double estimatedValue) {
        this.estimatedValue = estimatedValue;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }

    public Integer getDurationInMonths() {
        return durationInMonths;
    }

    public void setDurationInMonths(Integer durationInMonths) {
        this.durationInMonths = durationInMonths;
    }

    public Integer getDurationInDays() {
        return durationInDays;
    }

    public void setDurationInDays(Integer durationInDays) {
        this.durationInDays = durationInDays;
    }

    public String getProcedureType() {
        return procedureType;
    }

    public void setProcedureType(String procedureType) {
        this.procedureType = procedureType;
    }

    public String getA_ctw16() {
        return a_ctw16;
    }

    public void setA_ctw16(String a_ctw16) {
        this.a_ctw16 = a_ctw16;
    }

    public String getA_ctw17() {
        return a_ctw17;
    }

    public void setA_ctw17(String a_ctw17) {
        this.a_ctw17 = a_ctw17;
    }

    public String getA_ctw18() {
        return a_ctw18;
    }

    public void setA_ctw18(String a_ctw18) {
        this.a_ctw18 = a_ctw18;
    }

    public Date getA_ctw19() {
        return a_ctw19;
    }

    public void setA_ctw19(Date a_ctw19) {
        this.a_ctw19 = a_ctw19;
    }

    public String getA_ctw20() {
        return a_ctw20;
    }

    public void setA_ctw20(String a_ctw20) {
        this.a_ctw20 = a_ctw20;
    }

    public String getA_ctw21() {
        return a_ctw21;
    }

    public void setA_ctw21(String a_ctw21) {
        this.a_ctw21 = a_ctw21;
    }

    public String getA_ctw22() {
        return a_ctw22;
    }

    public void setA_ctw22(String a_ctw22) {
        this.a_ctw22 = a_ctw22;
    }

    public Date getA_ctw23() {
        return a_ctw23;
    }

    public void setA_ctw23(Date a_ctw23) {
        this.a_ctw23 = a_ctw23;
    }

    public String getA_ctw24() {
        return a_ctw24;
    }

    public void setA_ctw24(String a_ctw24) {
        this.a_ctw24 = a_ctw24;
    }

    public String getA_ctw25() {
        return a_ctw25;
    }

    public void setA_ctw25(String a_ctw25) {
        this.a_ctw25 = a_ctw25;
    }

    public String getA_ctw26() {
        return a_ctw26;
    }

    public void setA_ctw26(String a_ctw26) {
        this.a_ctw26 = a_ctw26;
    }

    public Integer getNumOfDays() {
        return numOfDays;
    }

    public void setNumOfDays(Integer numOfDays) {
        this.numOfDays = numOfDays;
    }

    public String getContractDuration() {
        return contractDuration;
    }

    public void setContractDuration(String contractDuration) {
        this.contractDuration = contractDuration;
    }

    public String getEcntransmission() {
        return ecntransmission;
    }

    public void setEcntransmission(String ecntransmission) {
        this.ecntransmission = ecntransmission;
    }

    public String getEcontractDocs() {
        return econtractDocs;
    }

    public void setEcontractDocs(String econtractDocs) {
        this.econtractDocs = econtractDocs;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public boolean isConnectionError() {
        return connectionError;
    }

    public void setConnectionError(boolean connectionError) {
        this.connectionError = connectionError;
    }

    public void eventSelectContractDuration(ValueChangeEvent vce) {
        contractDuration = (String) vce.getNewValue();
        if (contractDuration.equals("1")) {
            setNumbercd(true);
            setDatecd(false);
        } else if (contractDuration.equals("2")) {
            setNumbercd(false);
            setDatecd(true);
        }
    }


    public boolean isNumbercd() {
        return numbercd;
    }

    public void setNumbercd(boolean numbercd) {
        this.numbercd = numbercd;
    }

    public boolean isDatecd() {
        return datecd;
    }

    public void setDatecd(boolean datecd) {
        this.datecd = datecd;
    }


    
}
