package org.ellectra.gui.managebeans;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.ellectra.gui.utils.JSFUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.component.html.HtmlSelectOneListbox;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.WebServiceRef;
import org.ellectra.wskm.KeyManagerService;
//import org.ellectra.wsreg.UserRegistrationRequest.UserRole;
import org.ellectra.wsreg.UserRegistrationService;
import org.ellectra.wsws.ManageOrgService;

public class userregistration {
    @WebServiceRef(wsdlLocation = "http://localhost:8080/KeyManagerService/KeyManager?wsdl")
    private KeyManagerService service_2;
    @WebServiceRef(wsdlLocation = "http://localhost:18181/UserRegistrationService/UserRegistrationPort?wsdl")
    private UserRegistrationService service_1;
  //manage the organization list box  
  @WebServiceRef(wsdlLocation = "http://localhost:18181/ManageOrgService/ManageOrgPort?wsdl")
    private ManageOrgService service;

    private List organizations = Collections.EMPTY_LIST;
    private UIInput organizationslist;
    List <org.ellectra.wsws.OrgType> dInitalOrgList;
    
    
    //the rest of the fields
  String title;
  String genter;
  String gender;
  String name;
  String lastname;
  String atype;
  String role;
  String dname;
  String jtitle;
  String burl;
  String country;
  String town;
  String padd;
  String pcode;
  String pbox;
  String phone;
  String fax;
  String mobile;
  String pcon;
  String password;
  String orgname;
  String oname;
  String tnum;
  String caurl;
  String orgcoun;
  String orgtown;
  String orgadd;
  String orgpcode;
  String orgpo;
  String orgtel;
  String orgfax;
  String orgmob;
  String rolee[]; 
  int idone=0;
 private String usernamess;
 
  private void LoadOrganization()
    {
        try { // Call Web Service Operation
            org.ellectra.wsws.ManageOrgPortType port = service.getManageOrgPort();
            
            //  initialize WS operation arguments here
            org.ellectra.wsws.ManageOrgRequest part1 = new org.ellectra.wsws.ManageOrgRequest();
            part1.setAction("FR2_Org_ViewAll");
            part1.setActorSignature("123456");
            
            //call operation
            org.ellectra.wsws.ManageOrgResponse result = port.manageOrgOperation(part1);
            dInitalOrgList=result.getOrganisation();
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
        
    }
    public List getOrganizations() {
        List orgs = new ArrayList();
        LoadOrganization();
        int i;
            if (idone==0)
            {
                selectedone();
                idone=1;
            }
        for(i=0;i<dInitalOrgList.size();i++)
        {
            org.ellectra.wsws.OrgType dele=dInitalOrgList.get(i);
            String orgid = Integer.toString(dele.getId());
            SelectItem item = new SelectItem(orgid,dele.getOrganisationName());
            orgs.add(item);
            
        }    
        return orgs;
    }

    public void setOrganizations(List organizations) {
        this.organizations = organizations;
    }

    public UIInput getOrganizationslist() {
        return organizationslist;
    }

    public void setOrganizationslist(UIInput organizationslist) {
        this.organizationslist = organizationslist;
    }

  
    
            	public void orgSelected(ValueChangeEvent event) 
	
                        throws AbortProcessingException {
	int i;	
		//Get the selected region from the event
        
		String org = (String)event.getNewValue();
	for(i=0;i<dInitalOrgList.size();i++)
        {
            org.ellectra.wsws.OrgType dele=dInitalOrgList.get(i);
            String orgid = Integer.toString(dele.getId());
            if (orgid.equalsIgnoreCase(org))
            {
                setOname(dele.getOrganisationName());
                setTnum(dele.getTaxNumber());
                setCaurl(dele.getAuthorityURL());
                setOrgcoun(dele.getCountry());
                setOrgtown(dele.getCityName());
                setOrgadd(dele.getAddressLine1());
                setOrgpcode(dele.getPostCode());
                setOrgpo(dele.getPostBox());
                setOrgtel(dele.getDirectLine());
                setOrgfax(dele.getFax());
                setOrgmob(dele.getEmail());
            }
        }	
		
		//Force to render response phase so that any error messages DO NOT get
		//displayed. i.e. Skip update model phase. Use immediate="true" on the
		//component that calls this valueChangeListener so that it does not 
		//run any validation.
		FacesContext.getCurrentInstance().renderResponse();
		
	}
                
                public void selectedone() 
	
                        throws AbortProcessingException {
	int i;	
      	for(i=0;i<dInitalOrgList.size();i++)
        {
            org.ellectra.wsws.OrgType dele=dInitalOrgList.get(i);
            String orgid = Integer.toString(dele.getId());
            if (i==0)
            {
                setOname(dele.getOrganisationName());
                setTnum(dele.getTaxNumber());
                setCaurl(dele.getAuthorityURL());
                setOrgcoun(dele.getCountry());
                setOrgtown(dele.getCityName());
                setOrgadd(dele.getAddressLine1());
                setOrgpcode(dele.getPostCode());
                setOrgpo(dele.getPostBox());
                setOrgtel(dele.getDirectLine());
                setOrgfax(dele.getFax());
                setOrgmob(dele.getEmail());
            }
        }	
		
		//Force to render response phase so that any error messages DO NOT get
		//displayed. i.e. Skip update model phase. Use immediate="true" on the
		//component that calls this valueChangeListener so that it does not 
		//run any validation.
		FacesContext.getCurrentInstance().renderResponse();
		
	}
                
public String[] getRolee() {
	return rolee;
}

public void setRolee(String[] rolee) {
	this.rolee = rolee;
}

public String getTitle() {
	return title;
}

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

public String getGenter() {
	return genter;
}

public void setGenter(String genter) {
	this.genter = genter;
}

public String getName() {
	return name;
}

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

public String getLastname() {
	return lastname;
}

public void setLastname(String lastname) {
	this.lastname = lastname;
}

public String getAtype() {
	return atype;
}

public void setAtype(String atype) {
	this.atype = atype;
}

public String getRole() {
	return role;
}

public void setRole(String role) {
	this.role = role;
}

public String getDname() {
	return dname;
}

public void setDname(String dname) {
	this.dname = dname;
}

public String getJtitle() {
	return jtitle;
}

public void setJtitle(String jtitle) {
	this.jtitle = jtitle;
}

public String getBurl() {
	return burl;
}

public void setBurl(String burl) {
	this.burl = burl;
}

public String getCountry() {
	return country;
}

public void setCountry(String country) {
	this.country = country;
}

public String getTown() {
	return town;
}

public void setTown(String town) {
	this.town = town;
}

public String getPadd() {
	return padd;
}

public void setPadd(String padd) {
	this.padd = padd;
}

public String getPcode() {
	return pcode;
}

public void setPcode(String pcode) {
	this.pcode = pcode;
}

public String getPbox() {
	return pbox;
}

public void setPbox(String pbox) {
	this.pbox = pbox;
}

public String getPhone() {
	return phone;
}

public void setPhone(String phone) {
	this.phone = phone;
}

public String getFax() {
	return fax;
}

public void setFax(String fax) {
	this.fax = fax;
}

public String getMobile() {
	return mobile;
}

public void setMobile(String mobile) {
	this.mobile = mobile;
}

public String getPcon() {
	return pcon;
}

public void setPcon(String pcon) {
	this.pcon = pcon;
}

public String getPassword() {
	return password;
}

public void setPassword(String password) {
	this.password = password;
}

public String getOrgname() {
	return orgname;
}

public void setOrgname(String orgname) {
	this.orgname = orgname;
}

public String getOname() {
	return oname;
}

public void setOname(String oname) {
	this.oname = oname;
}

public String getTnum() {
	return tnum;
}

public void setTnum(String tnum) {
	this.tnum = tnum;
}

public String getCaurl() {
	return caurl;
}

public void setCaurl(String caurl) {
	this.caurl = caurl;
}

public String getOrgcoun() {
	return orgcoun;
}

public void setOrgcoun(String orgcoun) {
	this.orgcoun = orgcoun;
}

public String getOrgtown() {
	return orgtown;
}

public void setOrgtown(String orgtown) {
	this.orgtown = orgtown;
}

public String getOrgadd() {
	return orgadd;
}

public void setOrgadd(String orgadd) {
	this.orgadd = orgadd;
}

public String getOrgpcode() {
	return orgpcode;
}

public void setOrgpcode(String orgpcode) {
	this.orgpcode = orgpcode;
}

public String getOrgpo() {
	return orgpo;
}

public void setOrgpo(String orgpo) {
	this.orgpo = orgpo;
}

public String getOrgtel() {
	return orgtel;
}

public void setOrgtel(String orgtel) {
	this.orgtel = orgtel;
}

public String getOrgfax() {
	return orgfax;
}

public void setOrgfax(String orgfax) {
	this.orgfax = orgfax;
}

public String getOrgmob() {
	return orgmob;
}

public void setOrgmob(String orgmob) {
	this.orgmob = orgmob;
}

public String getGender() {
	return gender;
}

public void setGender(String gender) {
	this.gender = gender;
}
public String cancel()
{
    idone=0;
    FacesContext context = FacesContext.getCurrentInstance();
    context.renderResponse();
    return "cancel";
}
public String registeruser() {
	idone=0;
       // System.err.println("start reg");
    try { // Call Web Service Operation
        org.ellectra.wsreg.UserRegistrationPortType port = service_1.getUserRegistrationPort();

        org.ellectra.wsreg.UserRegistrationRequest part1 = new org.ellectra.wsreg.UserRegistrationRequest();


        part1.setOJSeSenderUserName("");
        part1.setAddressLine1(this.getPadd());
        part1.setAddressLine2(" ");
        part1.setBuyerURL(this.getCaurl());
        part1.setCityName(this.getTown());
        part1.setCountry(this.getCountry());
        part1.setDepartmentName(this.getDname());
        part1.setDirectLine(this.getPhone());
        part1.setEmail(this.getMobile());
        part1.setFax(this.getFax());
        part1.setFirstName(this.getName());
        part1.setGender(this.getGender());
        part1.setJobTitle(this.getJtitle());
        part1.setLanguagePreference("EN");
        part1.setLastName(this.getLastname());
        part1.setMobilePhone(this.getMobile());
        int aInt = Integer.parseInt(this.getOrgname());
        part1.setOrgid(aInt);
        part1.setPassword(this.getPassword());
        part1.setPostBox(this.getPbox());
        part1.setPostCode(this.getPcode());
        
        try { // Call Web Service Operation
            org.ellectra.wskm.KeyManager port2 = service_2.getKeyManagerPort();

            java.lang.String resultkm = port2.generateSignature();
            part1.setSignature(resultkm);

        } catch (Exception ex) {
            System.err.println("Result key manager error= "+ex.getLocalizedMessage());
            return "failure";
        }
        
        part1.setTitle(this.getTitle());
        part1.setUserName(this.getUsernamess());
        XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
        part1.setCreated(calendar);
      for (int i=0;i<rolee.length;i++)
        {
          //part1.getUserRole().getRole().add();
          List<String> dd=part1.getRole();
            dd.add(rolee[i]);
       }
        
        
      //  part1.setUserRole(part1.getUserRole());
        
        org.ellectra.wsreg.UserRegistrationResponse result = port.userRegistrationOperation(part1);
        //System.err.println("Result = "+result);
    } catch (Exception ex) {
        System.err.println("Result bpel error= "+ex.getLocalizedMessage());
        // TODO handle custom exceptions here
        return "failure";
    }
        // Clear all fields
        this.clearAllFields();
	return "success";
}


public String registezzzzzruser() {
	System.err.println("start");
    try { // Call Web Service Operation
        System.err.println("in");
        org.ellectra.wsreg.UserRegistrationPortType port = service_1.getUserRegistrationPort();
        
        org.ellectra.wsreg.UserRegistrationRequest part1 = new org.ellectra.wsreg.UserRegistrationRequest();
System.err.println("set");

        part1.setOJSeSenderUserName("");
        part1.setAddressLine1(" ");
        part1.setAddressLine2(" ");
        part1.setBuyerURL(" ");
        part1.setCityName(" ");
        part1.setCountry(" ");
        part1.setDepartmentName(" ");
        part1.setDirectLine(" ");
        part1.setEmail(" ");
        part1.setFax(" ");
        part1.setFirstName(" ");
        part1.setGender("MALE");
        part1.setJobTitle("MR");
        part1.setLanguagePreference("EN");
        part1.setLastName(" ");
        part1.setMobilePhone(" ");
        
        part1.setOrgid(2);
        part1.setPassword("tt");
        part1.setPostBox(" ");
        part1.setPostCode(" ");
        
//        try { // Call Web Service Operation
//            org.ellectra.wskm.KeyManager port2 = service_2.getKeyManagerPort();
//
//            java.lang.String resultkm = port2.generateSignature();
            part1.setSignature("resultkm");
//
//        } catch (Exception ex) {
//            System.err.println("Result key manager error= "+ex.getLocalizedMessage());
//            return "failure";
//        }
//        
        part1.setTitle("MR");
        part1.setUserName("test1");
        XMLGregorianCalendar calendar =DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
        part1.setCreated(calendar);
      //for (int i=0;i<rolee.length;i++)
       // {
          //part1.getUserRole().getRole().add(rolee[i]);
       //}
        System.err.println("Role s");
        //part1.getUserRole().getRole().
        String roledd="ADMIN";
        //part1.getUserRole().getRole().add(roledd);
        List<String> dd=part1.getRole();
        dd.add(roledd);
        
        //part1.setUserRole(part1.getUserRole());
        System.err.println("Role e");
        
        org.ellectra.wsreg.UserRegistrationResponse result = port.userRegistrationOperation(part1);
        
    } catch (Exception ex) {
        System.err.println("Result bpel error= "+ex.getMessage());
        ex.printStackTrace();
        return "failure";
    }

	return "success";
}

    public String getUsernamess() {
        return usernamess;
    }

    public void setUsernamess(String usernamess) {
        this.usernamess = usernamess;
    }
    

    public void validateURL (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
            String url = (String)value;
            //url1 = "/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix";
            //initially used but http://qq.com was error: 
            //String regex = "^((ftp|http(s?))\\:\\/\\/)?(www.|[a-zA-Z].)[a-zA-Z0-9\\-\\.]+\\.(com|edu|gov|mil|net|org|biz|info|name|museum|gr|us|ca|uk)(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\;\\?\\'\\\\+&%\\$#\\=~_\\-]+))*$";
           
            String regex = "^((ftp|http(s?))\\:\\/\\/)?[a-zA-Z0-9\\-\\.]+\\.(com|edu|gov|mil|net|org|biz|info|name|museum|gr|us|ca|uk)(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\;\\?\\'\\\\+&%\\$#\\=~_\\-]+))*$";            
            //String regex = "^(ftp|http[s]:\\/\\/)?([\\w\\-]+\\.)*[\\w\\-](\\:\\d+)?(/($|[a-zA-Z0-9\\.\\,\\;\\?\\'\\\\+&%\\$#\\=~_\\-]+))*$";
            if (!Pattern.matches(regex, url)) {
                    FacesMessage message = new FacesMessage("Invalid URL!");
                    context.addMessage("pinForm", message);
                    throw new ValidatorException(message);
            }
    }
    
    public void requiredCountry (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
            String country = (String)value;
            if (country.equals("???")) {
                    FacesMessage message = new FacesMessage("Country is an obligatory field!");
                    context.addMessage("pinForm", message);
                    throw new ValidatorException(message);
            }
    }
    
    /**
     *This method clears the content of personal fields
     */ 
    public void clearPersonalFields() {
        
//        FacesContext context = FacesContext.getCurrentInstance();
//        context.renderResponse();
        
        this.setName("");
        this.setLastname("");
        this.setDname("");
        this.setJtitle("");
        this.setBurl("");
        this.setTown("");
        this.setPadd("");
        this.setPbox("");
        this.setPhone("");
        this.setFax("");
        this.setMobile("");
        this.setPcode("");
        this.setCountry(null);
        this.setTitle(null);
        this.setGender(null);
        
        reDisplay();
    }
    
    /**
     *This method clears the content of profile fields
     */     
    public void clearAllFields() {
        this.setName("");
        this.setLastname("");
        this.setDname("");
        this.setJtitle("");
        this.setBurl("");
        this.setTown("");
        this.setPadd("");
        this.setPbox("");
        this.setPhone("");
        this.setFax("");
        this.setMobile("");
        this.setPcode("");
        this.setCountry(null);
        this.setTitle(null);
        this.setGender(null);
        
        this.setUsernamess("");
        this.setPassword("");
        this.setPcon("");
        
        this.setOrgadd("");
        this.setOrgcoun("");
        this.setOrgfax("");
        this.setOrgmob("");
        this.setOrgname("");
        this.setOrgpcode("");
        this.setOrgpo("");
        this.setOrgtel("");
        this.setOrgtown("");
//        FacesContext context = FacesContext.getCurrentInstance();
//        context.renderResponse();

        
   
    }
    
    public void reDisplay() {
        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        ViewHandler viewHandler = application.getViewHandler();
        UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
        context.setViewRoot(viewRoot);
        context.renderResponse(); //Optional
    }
    
    /**
     *This method clears the content of profile fields
     */     
    public void clearProfileFields() {
        
//        FacesContext context = FacesContext.getCurrentInstance();
//        context.renderResponse();
        
        this.setUsernamess("");
        this.setPassword("");
        this.setPcon("");
        
        reDisplay();
    }

}
