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.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.ws.WebServiceRef;
import org.ellectra.wskm.KeyManagerService;
//import userOrgId.ellectra.wsreg.UserRegistrationRequest.UserRole;
import org.ellectra.wsmu.ManageUserService;
import org.ellectra.wsmu.UserAccountType;
import org.ellectra.wsreg.UserRegistrationService;
import org.ellectra.wsws.ManageOrgService;

public class userprofile {

	@WebServiceRef(wsdlLocation = "http://localhost:18181/ManageUserService/ManageUserPort?wsdl")
	private ManageUserService 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 userOrgId;

	String rolee[];
	private int idone = 0;
	int iUIDToLoad = -1;
	int icachedid;
	public String password2;
	public String qjeu;
	public String pemail2;
	public String lang2;
	UserAccountType dCurrentUser;
	private String username;
        // booleans to denote that an update button was pressed
        private String title2;

	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 (getIdone() == 0) {
//			selectedone();
                        SelectOrgForUser();
			setIdone(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);

		}
                System.out.println(orgs.toString());
		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();
		setUserOrgId(String.valueOf(userOrgId));
		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;
		//LoadOrganization();
		//Get the selected region from the event
		//String userOrgId = (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 (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());
			}
		//SelectItem item = new SelectItem(orgid,dele.getOrganisationName());
		//SelectItem item = new SelectItem("1","dd2");
		//orgs.add(item);
		}

		//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();

	}

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

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

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

	public String LoadUser() {
		try { // Call Web Service Operation
			org.ellectra.wsmu.ManageUserPortType port = service_1.getManageUserPort();

			org.ellectra.wsmu.ManageUserRequest part1 = new org.ellectra.wsmu.ManageUserRequest();
			part1.setAction("FR2_UserAcc_Read");
			part1.setActorSignature(GetUserSignatureFromSession());
			part1.setUserId(GetUserIDFromSession());//iuserselected);
			//System.err.print("details"+
			org.ellectra.wsmu.ManageUserResponse result = port.manageUserOperation(part1);
			List<UserAccountType> dAcc = result.getUserAccount();
			dCurrentUser = dAcc.get(0);
			icachedid = dCurrentUser.getUserId();
			SetUserDetails();
                        return "editprofilelink";
		} catch (Exception ex) {
			System.err.print("Error on profile" + ex.getLocalizedMessage());
		}
                return "editprofilelink";
	}
        
	/**
	 * Calls the BPEL to update a user profile
	 * @return a string denoting success or failure
	 */
	public String updateUser () {
		
		try { // Call Web Service Operation
		   org.ellectra.wsmu.ManageUserPortType port = service_1.getManageUserPort();
			 // TODO initialize WS operation arguments here
			org.ellectra.wsmu.ManageUserRequest part1 = new org.ellectra.wsmu.ManageUserRequest();
			part1.setAction("FR2_UserAcc_Update");
			
			part1.setOJSeSenderUserName("");
			part1.setAddressLine1(this.getPadd());
			part1.setAddressLine2(" ");
			part1.setApproved(true);
			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(this.getLang2());
			part1.setLastName(this.getLastname());
			part1.setMobilePhone(this.getMobile());
//			System.out.println("ORG NAME: " + this.getOrgname());
//			int aInt = Integer.parseInt(this.getOrgname());
//			part1.setOrgId(aInt);
			part1.setPassword(this.getPassword());
			part1.setPostBox(this.getPbox());
			part1.setPostCode(this.getPcode());
                        
			part1.setTitle(this.getTitle());
			part1.setUserName(this.getUsername());
			
			part1.setActorSignature(GetUserSignatureFromSession());
			part1.setUserId(GetUserIDFromSession());//iuserselected);
			
			// TODO process result here
			org.ellectra.wsmu.ManageUserResponse result = port.manageUserOperation(part1);
			System.out.println("Result = " + result);
		   
		} catch (Exception ex) {
			ex.printStackTrace();
			return "failure";
		}
		
		return "updated";
	}
        
        /**
	 * Clears the Personal Fields
	 */
	public void clearPersonalFields () {

            this.name       = "";
            this.lastname   = "";
            this.dname      = "";
            this.jtitle     = "";
            this.burl       = "";
            this.town       = "";
            this.padd       = "";
            this.pcode      = "";
            this.pbox       = "";
            this.phone      = "";
            this.fax        = "";
            this.mobile     = "";
            
            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
	}
        /**
	 * Clears the Profile Fields
	 */
        public void clearProfileFields () {

            this.username   = "";
            this.qjeu       = "";
            this.pemail2    = "";
            this.password   = "";
            this.password2  = "";
            
            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
	}
        
        /**
	 * Cancels an update procedure by re-setting the user data
	 */
        public String cancelUpdate () {

            this.SetUserDetails();
            
            return "cancelled_update";
                 
	}

	public void SetUserDetails() {
                
            title = dCurrentUser.getTitle();
            title2=dCurrentUser.getTitle();
            genter = dCurrentUser.getGender();
            gender = dCurrentUser.getGender();
            name = dCurrentUser.getFirstName();
            lastname = dCurrentUser.getLastName();
            dname = dCurrentUser.getDepartmentName();
            jtitle = dCurrentUser.getJobTitle();
            burl = dCurrentUser.getBuyerURL();
            country = dCurrentUser.getCountry();
            town = dCurrentUser.getCityName();
            padd = dCurrentUser.getAddressLine1();
            pcode = dCurrentUser.getPostCode();
            pbox = dCurrentUser.getPostBox();
            phone = dCurrentUser.getDirectLine();
            fax = dCurrentUser.getFax();
            mobile = dCurrentUser.getEmail();
            qjeu = dCurrentUser.getOJSeSenderUserName();
            lang2 = dCurrentUser.getLanguagePreference();
            lang2 = dCurrentUser.getLanguagePreference();
            qjeu = dCurrentUser.getOJSeSenderUserName();
            pemail2 = dCurrentUser.getEmail();
            setUsername(dCurrentUser.getUserName());
            password = dCurrentUser.getPassword();
            password2 = dCurrentUser.getPassword();
            SelectOrgForUser();
	}

	public void SelectOrgForUser() {
		userOrgId = Integer.toString(dCurrentUser.getOrgId());

		for (int i = 0; i < dInitalOrgList.size(); i++) {
                        System.out.println(i);
			org.ellectra.wsws.OrgType dele = dInitalOrgList.get(i);
			String orgid = Integer.toString(dele.getId());
                        System.out.println("\t" + dele.getOrganisationName());
                        if (orgid.equalsIgnoreCase(userOrgId)) {
                                System.out.println("\tSELECTED Oname: " + dele.getOrganisationName());
				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());
			}
		}
	}

	public String[] getRolee() {
		return rolee;
	}

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

	public String getTitle() {

//       if( getIdone()==0)
		//      {
		//LoadUser();
		//    }

		//  if (icachedid==GetUserIDFromSession())
		//  {}
		//  else
		// {
		//  LoadUser();
		//}
            
		return title;
	}
        
        public void requiredCountry (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
                String country1 = (String)value;
                if (country1.equals("???")) {
                        FacesMessage message = new FacesMessage("Country is an obligatory field!");
                        context.addMessage("pinForm", message);
                        throw new ValidatorException(message);
                }
        }
        
        public void validateEmail (FacesContext context, UIComponent toValidate, Object value) throws ValidatorException {
		String email = (String)value;
		if (email.indexOf("@") < 0) {
			FacesMessage message = new FacesMessage("Invalid e-mail address!");
			context.addMessage("pinForm", message);
			throw new ValidatorException(message);
		}
	}
        
        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 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() {
            System.err.println("ORG NAME:" + orgname);
		return orgname;
	}

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

	public String getOname() {
                this.SelectOrgForUser();
		return oname;
	}

	public void setOname(String oname) {
            System.out.println(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() {
		setIdone(0);
                FacesContext context = FacesContext.getCurrentInstance();
                context.renderResponse();
		return "cancel";
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getQjeu() {
		return qjeu;
	}

	public void setQjeu(String qjeu) {
		this.qjeu = qjeu;
	}

	public String getPemail2() {
		return pemail2;
	}

	public void setPemail2(String pemail2) {
		this.pemail2 = pemail2;
	}

	public String getLang2() {
		return lang2;
	}

	public void setLang2(String lang2) {
		this.lang2 = lang2;
	}

	public int getIdone() {
		return idone;
	}

	public void setIdone(int idone) {
		this.idone = idone;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

        public String getTitle2() {
            return title2;
        }

        public void setTitle2(String title2) {
            this.title2 = title2;
        }
        
        public String getUserOrgId() {
            return userOrgId;
        }

        public void setUserOrgId(String userOrgId) {
            this.userOrgId = userOrgId;
        }
}
