/*
 * Login.java
 * 
 * Created on Sep 21, 2007, 2:53:16 PM
 * 
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package org.ellectra.gui.managebeans;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;

import org.ellectra.fileutils.FileUtil;
import org.ellectra.gui.utils.JSFUtils;
import org.ellectra.wscaa.AuthenAuthoService;
import org.ellectra.wscaa.UcResponse.Role;
import org.ellectra.clientside.generatekeys;

import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.ellectra.certhelper.certreader;
//import //org.ellectra.wsmu.ManageUserRequest.UserRole;
/**
 *
 * @author tdi
 */
public class logincert {

    @WebServiceRef(wsdlLocation = "http://localhost:18181/Authen_AuthoService/Authen_AuthoPort?wsdl")
    private AuthenAuthoService service;
    String name;
    String password;
    private String szOrg;
    private String szLang;
    String dresult;
    private String szsignature;
    private int userid;
    private Role duserrole;
    
    private String part_ca_home;
    private String part_my_calls;
    
    private boolean ca;
    private boolean admin;
    private boolean poarole;
    private boolean poorole;
    private boolean poerole;
    private boolean eorole;
    
    private boolean myCallsRendered;

 private UploadedFile uploadedFile;
    
    private String szPath ="/Users/gpa/";
    
    public logincert() {
        super();
        poarole = false;
        poorole = false;
        poerole = false;
        eorole = false;
        
        myCallsRendered = false;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {


        this.password = password;
    }

    public void reset() {
        setAdmin(false);
        setCa(false);
        setEorole(false);

        setPoorole(false);
        setPoarole(false);
        setPoerole(false);
    }

    public String loginUser() {
    	generatekeys dd = new generatekeys();
        dd.GenerateAllKeys();
        reset();
        String filename="";
        pathSettings dset=new pathSettings();
        szPath=dset.GetUploadDirectory();
        String szPath2=dset.GetCertDirectory();
        String szfilename2="";
        String szfilename3="";
        String szpath22=dset.GetUploadDirectory();
        try {
            File uniqueFile = new File(szPath+FileUtil.trimFilePath(uploadedFile.getName()));
            FileUtil.write(uniqueFile, uploadedFile.getInputStream());
            filename = szPath+FileUtil.trimFilePath(uploadedFile.getName());
            szfilename2=szPath2+FileUtil.trimFilePath(uploadedFile.getName());
            szfilename3=szpath22+FileUtil.trimFilePath(uploadedFile.getName());
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                FacesMessage.SEVERITY_INFO, "File upload succeed!", null));
            
        } catch (IOException e) {

            
            FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
            System.err.println("Certificate Error");
            
            e.printStackTrace();
        }
        System.err.println("Checking certificate details "+filename+" "+szfilename2);
        if (CheckCertificates(filename,szfilename2)==false)
        {
        	
        	System.err.println("error Checking certificate details ");
        	return "failure";
        }
        certreader cc= new certreader();
        cc.ReadCert(filename);
        System.out.println("Certificate Name - "+cc.GetName());
        System.out.println("Certificate Surname - "+cc.GetSurname());
        try {
            org.ellectra.wscaa.AuthenAuthoPortType port = service.getAuthenAuthoPort();
            //String dd;
            //dd.(name)

            org.ellectra.wscaa.UcRequest part1 = new org.ellectra.wscaa.UcRequest();
            part1.setAction("FR3_CertAuthenticate");
            part1.setFirstname(cc.GetName());
            part1.setLastname(cc.GetSurname());

            ////////////////////////////
            //we dont use this just initialize
            part1.setSignature("ddd");
            part1.setOperation("ddd");
            /////////////////////////////////////
            //Object xmldate = null;
            //part1.setLastLogin(null);
            // part1.se

            org.ellectra.wscaa.UcResponse result = port.authenAuthoOperation(part1);
            //System.out.println("Result = "+result);
            System.err.println("Result ok ");
            if (result.isReturn() == true) {
            	System.err.println("true we are in");
            	setSzOrg(result.getOrgName());
                setSzLang(result.getLanguage());
                setSzsignature(result.getSignature());
                setUserid((int) result.getUserAccountID());
                setDuserrole(result.getRole());
                setName(result.getUsername());
                System.err.println("store on sessions");
                ////////////////////////////////////
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINUSER", getName());
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "CALLTENDERID", "458");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINSIGNATURE", getSzsignature());
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINORGANIZATION", result.getOrgName());
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLE", "GUEST");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERID", "TENDERID");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "TENDERIDI", "10");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINUSERID", Integer.toString(getUserid()));
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGIN", "success");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEADMIN", "NO");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEPOA", "NO");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEPOO", "NO");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEPOE", "NO");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEEO", "NO");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "MAINCPVFORCREATETENDER", " ");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "MAINCPVFORSEARCH", " ");

                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "NUTSFORCREATETENDER", " ");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "VOCFORCREATETENDER", " ");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "MAINCPVFORPIN", " ");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "NUTSFORPIN", " ");
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "MAINCPVFORCN", " ");
                System.err.println("get roles");
                Role d = result.getRole();
                List<String> Roles = d.getUcrole();

                StringBuffer cahome = new StringBuffer("Welcome " + this.getName() + " to your home page. ");
                StringBuffer myCalls = new StringBuffer("");

                String continuecahome = "This is your personal Webpage, which allows you to obtain information ";

                String line1 = "and manage your Calls for Tenders";
                String line2 = "on Calls for Tenders and submit your proposals. ";
                String line3 = "Online communication with tenderers and colleagues is supported. ";

                String lineProfile = "To modify your profile, please use the following link: ";
                String line4 = "In this section you can obtain information and manage your existing Calls.";
                System.err.println("for starts");
                for (int i = 0; i < Roles.size(); i++) {
                    String dget = Roles.get(i);
                    if (dget.equalsIgnoreCase("ADMIN")) {
                        setCa(false);
                        setAdmin(true);
                        
                        myCalls.append("Welcome " + this.getName() + " to the administration console of the electronic Public Procurement Solution (ePP). Please use the menu items on the left to manage and configure the ePP Solution.");

                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLE", "NOGUEST");
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEADMIN", "ADMIN");
                    }

                    if (dget.equalsIgnoreCase("PROCUREMENT_OFFICER_ADMINISTRATIVE")) {
                        cahome.append(continuecahome);
                        cahome.append(line1);
                        cahome.append(" and create new Calls. ");
                        cahome.append(line3);
                        cahome.append(lineProfile);
                        
                        myCallsRendered = true;
                        myCalls.append("In this section you can create new Calls for Tenders, as well as, obtain information and manage your existing Calls.");
                        setAdmin(false);
                        setCa(true);
                        setPoarole(true);

                        setPoorole(false);
                        setPoerole(false);
                        setEorole(false);
                        
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLE", "NOGUEST");
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEPOA", "POA");
                    }

                    if (dget.equalsIgnoreCase("PROCUREMENT_OFFICER_OPENING")) {
                        cahome.append(continuecahome);
                        cahome.append(line1);
                        cahome.append(". ");
                        cahome.append(line3);
                        cahome.append(lineProfile);

                        myCallsRendered = true;
                        myCalls.append(line4);
                        setAdmin(false);
                        setCa(true);
                        setPoorole(true);

                        setPoarole(false);
                        setPoerole(false);
                        setEorole(false);
                        
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLE", "NOGUEST");
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEPOO", "POO");
                    }

                    if (dget.equalsIgnoreCase("PROCUREMENT_OFFICER_EVALUATING")) {
                        cahome.append(continuecahome);
                        cahome.append(line1);
                        cahome.append(". ");
                        cahome.append(line3);
                        cahome.append(lineProfile);

                        myCallsRendered = true;
                        myCalls.append(line4);
                        setAdmin(false);
                        setCa(true);
                        setPoerole(true);

                        setPoorole(false);
                        setPoarole(false);
                        setEorole(false);
                        
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLE", "NOGUEST");
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEPOE", "POE");
                    }

                    if (dget.equalsIgnoreCase("ECONOMIC_OPERATOR")) {
                        cahome.append(continuecahome);
                        cahome.append(line2);
                        cahome.append(line3);
                        cahome.append(lineProfile);

                        myCallsRendered = true;
                        myCalls.append(line4);
                        setAdmin(false);
                        setCa(false);
                        setEorole(true);

                        setPoorole(false);
                        setPoarole(false);
                        setPoerole(false);
                        
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLE", "NOGUEST");
                        JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGINROLEEO", "EO");
                    }
                    if (dget.equalsIgnoreCase("GUEST")) {
                        cahome.append(lineProfile);
                        myCallsRendered = false;
                    }
                    setPart_ca_home(cahome.toString());
                    setPart_my_calls(myCalls.toString());

                }
                System.err.println("Return ok ");
                return "success";
            } else {
                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGIN", "failure");
                System.err.println("Return problem on login");
                return "failure";
            }
        } catch (Exception ex) {

            // FacesContext facesContext = FacesContext.getCurrentInstance();
            //FacesMessage facesMessage = new FacesMessage(
            //   "You have entered an invalid user name and/or password");
            //facesContext.addMessage("loginForm", facesMessage);
            JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "LOGIN", "failure");
            System.err.println("catch error");
            return "wsfailure";
        }
//return "failure";
//        if("PO".equalsIgnoreCase(getName()))
//        {
//                
//                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "ROLE", "POA");
//                return "success";
//                
//        }
//        
//        if("EO".equalsIgnoreCase(getName()))
//        {
//            
//                JSFUtils.storeOnSession(FacesContext.getCurrentInstance(), "ROLE", "EO");
//                return "success";
//                
//        }
//        

    }

    public String getSzOrg() {
        return szOrg;
    }

    public void setSzOrg(String szOrg) {
        this.szOrg = szOrg;
    }

    public String getSzLang() {
        return szLang;
    }

    public void setSzLang(String szLang) {
        this.szLang = szLang;
    }

    public String getDresult() {
        return dresult;
    }

    public void setDresult(String dresult) {
        this.dresult = dresult;
    }

    public String getSzsignature() {
        return szsignature;
    }

    public void setSzsignature(String szsignature) {
        this.szsignature = szsignature;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public Role getDuserrole() {
        return duserrole;
    }

    public void setDuserrole(Role duserrole) {


        this.duserrole = duserrole;
    }

    public String getPart_ca_home() {
        return part_ca_home;
    }

    public void setPart_ca_home(String ca_home_line1) {
        this.part_ca_home = ca_home_line1;
    }

    public String getPart_my_calls() {
        return part_my_calls;
    }

    public void setPart_my_calls(String part_my_calls) {
        this.part_my_calls = part_my_calls;
    }

    public boolean isCa() {
        return ca;
    }

    public void setCa(boolean ca) {
        this.ca = ca;
    }

    public boolean isPoarole() {
        return poarole;
    }

    public void setPoarole(boolean poarole) {
        this.poarole = poarole;
    }

    public boolean isPoorole() {
        return poorole;
    }

    public void setPoorole(boolean poorole) {
        this.poorole = poorole;
    }

    public boolean isPoerole() {
        return poerole;
    }

    public void setPoerole(boolean poerole) {
        this.poerole = poerole;
    }

    public boolean isEorole() {
        return eorole;
    }

    public void setEorole(boolean eorole) {
        this.eorole = eorole;
    }

    public boolean isAdmin() {
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    public boolean isMyCallsRendered() {
        return myCallsRendered;
    }

    public void setMyCallsRendered(boolean myCallsRendered) {
        this.myCallsRendered = myCallsRendered;
    }
    
    public UploadedFile getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
    
    private boolean CheckCertificates(String szc1,String szc2)
    {
    	File dd1= new File(szc1);
		File dd2= new File(szc2);
		
			if(CheckPrivateKey(dd1,dd2))
				return true;
			else
				return false;
		
    }
    private boolean CheckPrivateKey(File left, File right)
    {
        if (left == null)
        	{
        	System.err.print("null error");
        	return false;
        	}
        if (right == null)
        	{
        	
        	System.err.print("null error");
        	return false;
        	}
        if (!left.exists()){
        	System.err.print("existance error");
        	return false;
        }
        if (!right.exists()){
        	System.err.print("existance error");
        	return false;
        }
        
        if (left.length() != right.length()){
        	System.err.print("length error");
        	return false;
        }
            
        
        FileInputStream lin = null;
		try {
			lin = new FileInputStream(left);
		} catch (FileNotFoundException e) {
			return false;
		}
        FileInputStream rin = null;
		try {
			rin = new FileInputStream(right);
		} catch (FileNotFoundException e) {
			return false;
		}
        try
        {
            byte[] lbuffer = new byte[4096];
            byte[] rbuffer = new byte[lbuffer.length];
            for (int lcount = 0; (lcount = lin.read(lbuffer)) > 0;)
            {
                int bytesRead = 0;
                for (int rcount = 0; (rcount = rin.read(rbuffer, bytesRead, lcount - bytesRead)) > 0;)
                {
                    bytesRead += rcount;
                }
                for (int byteIndex = 0; byteIndex < lcount; byteIndex++)
                {
                    if (lbuffer[byteIndex] != rbuffer[byteIndex])
                        return false;
                }
            }
        } catch (IOException e) {
			return false;
		}
        finally
        {
            try {
				lin.close();
			} catch (IOException e) {
				return false;
			}
            try {
				rin.close();
			} catch (IOException e) {
				return false;
			}
        }
        return true;
    }


    private boolean CheckFileMetaData(File source ,File destiny){
    	 
        boolean is=true;
        if (!destiny.exists()){
            is=false;
        }else{
 
            long lengthSource=source.length();
            long lengthDestiny=destiny.length();
            long modifiedSource=source.lastModified();
            long modifiedDestiny=destiny.lastModified();
            if ((lengthSource!=lengthDestiny)||(modifiedSource>modifiedDestiny)){
                is=false;
            }
        }
        return is;
    }
}