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

import java.util.ArrayList;
import java.util.Date;
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.ellectra.gui.utils.JSFUtils;
import org.ellectra.wscheckunlock.CheckUnlockingService;
import org.ellectra.wsunlockmytender.UnlockTenderService;
//import org.ellectra.wsut.Response.Userlist;
import org.ellectra.wsvassignpo.ViewAssignedPOsService;

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

    @WebServiceRef(wsdlLocation = "http://localhost:18181/UnlockTenderService/UnlockTenderPort?wsdl")
    private UnlockTenderService service_1;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/CheckUnlockingService/CheckUnlockingPort?wsdl")
    private CheckUnlockingService service;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/ViewAssignedPOsService/ViewAssignedPOsPort?wsdl")
    private ViewAssignedPOsService service_3;
    private UIData udata = null;
    private ArrayList<unlocklist> ulist = new ArrayList();
    private Date datestart;
    private Date dateend;
    private int phase;
    int icompleteunlocked;// = 0;
    //private boolean bshowneedunlock = true;
    private String unlockStringText;// = "";
    private String unlockingStatusStringText;

    private int GetUserIDFromSession() {
        String dtemp = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINUSERID");
        return Integer.valueOf(dtemp).intValue();
    }

    private int GetCallForTenderIDFromSession() {
        String dtemp = (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID");
        return Integer.valueOf(dtemp).intValue();
    }

    private String GetUserSigFromSession() {
        return (String) JSFUtils.retrieveOnSession(FacesContext.getCurrentInstance(), "LOGINSIGNATURE");
    }
    
    private void PopulateList() {
        System.err.print("Population of list starts");
        icompleteunlocked = 0;

        try { // Call Web Service Operation
            org.ellectra.wscheckunlock.CheckUnlockingPortType port = service.getCheckUnlockingPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wscheckunlock.CheckUnlockingRequest part1 = new org.ellectra.wscheckunlock.CheckUnlockingRequest();
            part1.setCallForTenderID(GetCallForTenderIDFromSession());
            part1.setActorSignature(GetUserSigFromSession());
            
            System.err.print(GetCallForTenderIDFromSession() + " " + GetUserSigFromSession());
            // TODO process result here
            org.ellectra.wscheckunlock.CheckUnlockingResponse result = port.checkUnlockingOperation(part1);

            List<org.ellectra.wscheckunlock.PoOpenType> dd = result.getPOopen();
            ulist.clear();
            for (int i = 0; i < dd.size(); i++) {
                org.ellectra.wscheckunlock.PoOpenType ditem = new org.ellectra.wscheckunlock.PoOpenType();
                ditem = dd.get(i);
                
                unlocklist pp = new unlocklist();
                pp.setIuserid(ditem.getUserAccountID());
                System.err.print(ditem.getFirstName() + " " + ditem.getLastName() + "id=" + ditem.getUserAccountID());
                pp.setFullname(ditem.getFirstName() + " " + ditem.getLastName());
                pp.setTpid(ditem.getUserUnlockingRecordID());

                if (ditem.isIsMyUnlockRecord()) {
                    if (ditem.isStatus()) { //this user has confirmed unlocking
                        pp.setShowb(false);
                        pp.setShows(true);
                        pp.setStatus("Complete");
                        unlockingStatusStringText = "You have already confirmed your unlocking for tenders of this call.";
                        icompleteunlocked = icompleteunlocked + 1;
                    } else {
                        pp.setShowb(true);
                        pp.setShows(false);
                        pp.setStatus("Incomplete");
                        unlockingStatusStringText = "Please press the \"UNLOCK\" link to confirm your accord for unlocking tenders.";
                    }
                } else {    //for any other po_open 
                    pp.setShowb(false);
                    pp.setShows(true);
                    if (ditem.isStatus()) {
                        pp.setStatus("Complete");
                        icompleteunlocked = icompleteunlocked + 1;
                    } 
                    else
                        pp.setStatus("Incomplete");
                }
                ulist.add(pp);
            //pp.setShowb();
        }
        int iminstaff = GetMinStaff();
        if (icompleteunlocked >= iminstaff) {
            //setBshowneedunlock(false);
            unlockingStatusStringText = "Tenders are already unlocked.";
            unlockStringText = "For the Call to be unlocked: [ " + String.valueOf(iminstaff) + " ] POs with role Opening need to confirm, at the moment all the POs needed to unlock the tenders for this call have confirmed unlocking.";
        }
        else {
            //setBshowneedunlock(true);
            unlockStringText = "For the Call to be unlocked: [ " + String.valueOf(iminstaff) + " ] POs with role Opening need to confirm, at the moment only [ " + String.valueOf(icompleteunlocked) + " ] Po's had confirmed unlocking.";
        }
        
//        if (iminstaff >= icompleteunlocked) {
//            setBshowneedunlock(true);
//            unlockStringText = "For the Call to be unlocked [" + String.valueOf(iminstaff) + "] POs with role Opening need to confirm, at the moment only " + String.valueOf(icompleteunlocked) + " Po's had confirmed unlocking";
//            unlockingStatusStringText = "Please press the \"UNLOCK\" link to confirm your accord for unlocking tenders.";
//        } else {
//            setBshowneedunlock(false);
//            unlockStringText = "For the Call to be unlocked [" + String.valueOf(iminstaff) + "] POs with role Opening need to confirm, at the moment all the POs needed to unlock the tenders for this call have confirmed unlocking";
//            unlockingStatusStringText = "Tenders are already unlocked";
//        }

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

      /**
     * Use this function to get Minimum Number for po_open for unlocking 
     * @return
     */
    public int GetMinStaff() {
        int iMin = 0;
        try { // Call Web Service Operation
            org.ellectra.wsvassignpo.ViewAssignedPOsPortType port = service_3.getViewAssignedPOsPort();

            org.ellectra.wsvassignpo.ViewAssignedPOsRequest part1 = new org.ellectra.wsvassignpo.ViewAssignedPOsRequest();
            part1.setActorSignature(GetUserSigFromSession());
            part1.setCallForTenderID(GetCallForTenderIDFromSession());
            
            org.ellectra.wsvassignpo.ViewAssignedPOsResponse result = port.viewAssignedPOsOperation(part1);
            iMin = result.getMinNumOfPOsForOpen();

        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.err.println("UNLOCK TENDER: GET_MIN_STAFF EXCEPTION");
            ex.printStackTrace();
        }
        return iMin;
    }
    
    private int GetPhaseIDFromWS() {

//        try { // Call Web Service Operation
//            org.ellectra.wsut.UnlockTenderService service = new org.ellectra.wsut.UnlockTenderService();
//            org.ellectra.wsut.UnlockTenderPortType port = service.getUnlockTenderPort();
//
//            org.ellectra.wsut.Request request = new org.ellectra.wsut.Request();
//            request.setAction("GETDETAILS");
//            org.ellectra.wsut.Response result = port.unlockTenderOperation(request);
//            return result.getPhasenumber();
//        } catch (Exception ex) {
        return -1;
//        }

    }
    
    /**
     * Confirm user unlocking
     */
    public String unlockusertender() {
        unlocklist Selected = (unlocklist) this.getUdata().getRowData();
        int tid = Selected.getTpid();

        try { // Call Web Service Operation
            org.ellectra.wsunlockmytender.UnlockTenderPortType port = service_1.getUnlockTenderPort();
            // TODO initialize WS operation arguments here
            org.ellectra.wsunlockmytender.UnlockTenderRequest part1 = new org.ellectra.wsunlockmytender.UnlockTenderRequest();
            part1.setCallForTenderID(GetCallForTenderIDFromSession());
            part1.setActorSignature(GetUserSigFromSession());
            part1.setUserUnlockingRecordID(tid);
            // TODO process result here
            org.ellectra.wsunlockmytender.UnlockTenderResponse result = port.unlockTenderOperation(part1);
            System.out.println("UNLOCKTENDER: UNLOCK BPEL: " + result.isReturn());
            System.out.println("UNLOCKTENDER: UNLOCK BPEL: " + result.getReturnMessage());
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            System.out.println("Result error on unlock= " + ex.getLocalizedMessage());
        }


//        int pid=GetPhaseIDFromWS();
//        try { // Call Web Service Operation
//            org.ellectra.wsut.UnlockTenderService service = new org.ellectra.wsut.UnlockTenderService();
//            org.ellectra.wsut.UnlockTenderPortType port = service.getUnlockTenderPort();
//
//            org.ellectra.wsut.Request request = new org.ellectra.wsut.Request();
//            request.setAction("UNLOCK");
//            request.setPhase(pid);
//            request.setTenderid(tid);
//            org.ellectra.wsut.Response result = port.unlockTenderOperation(request);
//            
//        } catch (Exception ex) {
//            return "error";
//        }
        return "confirmunlock";
    }
    
    public String LoadUnlockScreen() {
        String dValue = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id");
        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID", dValue);

        return "unlockscr";
    }
    
    
    ///////////////////////////////////////////////// OK /////////////////////////////////
    ///getters and setters
    public UIData getUdata() {
        return udata;
    }

    public void setUdata(UIData udata) {
        this.udata = udata;
    }

    public ArrayList<unlocklist> getUlist() {
        //PopulateList();
        return ulist;
    }

    public void setUlist(ArrayList<unlocklist> ulist) {
        this.ulist = ulist;
    }

    public Date getDatestart() {
        return datestart;
    }

    public void setDatestart(Date datestart) {
        this.datestart = datestart;
    }

    public Date getDateend() {
        return dateend;
    }

    public void setDateend(Date dateend) {
        this.dateend = dateend;
    }

    public int getPhase() {
        return phase;
    }

    public void setPhase(int phase) {
        this.phase = phase;
    }

//    public boolean isBshowneedunlock() {
//        return bshowneedunlock;
//    }
//
//    public void setBshowneedunlock(boolean bshowneedunlock) {
//        this.bshowneedunlock = bshowneedunlock;
//    }

    public String getUnlockStringText() {
        return unlockStringText;
    }

    public void setUnlockStringText(String unlockStringText) {
        this.unlockStringText = unlockStringText;
    }

    public String getUnlockingStatusStringText() {
        PopulateList();
        return unlockingStatusStringText;
    }

    public void setUnlockingStatusStringText(String unlockingStatusStringText) {
        this.unlockingStatusStringText = unlockingStatusStringText;
    }
}
