/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ellectra.gui.managebeans;

//import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.xml.ws.WebServiceRef;
//import org.ellectra.gui.utils.DtoComparator;
import org.ellectra.wsws.ManageOrgService;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;
/**
 *
 * @author tdi
 */
public class organizationmanager {
    @WebServiceRef(wsdlLocation = "http://localhost:18181/ManageOrgService/ManageOrgPort?wsdl")
    private ManageOrgService service;
    public UIData orgdata = null;
	
    public ArrayList<organisationlist> aorg= new ArrayList();
    public int id;
    public String organization;
    public String organizationname;
    public String taxnumber;
    public String url;
    public String country;
    public String town;
    public String padd;
    public String pobox;
    public String postcode;
    public String tele;
    public String fax;
    public String email;
    public String searchcc="0";
    public String szsearchname;
    public String sort="0"; 
    
    
    public UIData getOrgdata() {
        return orgdata;
    }

    public void setOrgdata(UIData orgdata) {
        this.orgdata = orgdata;
    }

    public

    ArrayList<organisationlist> getAorg() {
        
        PopulateList();
        
        return aorg;
    }

    public void setAorg(ArrayList<organisationlist> aorg) {
        this.aorg = aorg;
    }
	
    public void dosearch()
    {
        PopulateList();
    }
    public void PopulateList()
    {
        
        aorg.clear();
	List <org.ellectra.wsws.OrgType> dInitalOrgList;
        int i;
        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();
            
         
        for(i=0;i<dInitalOrgList.size();i++)
        {
            org.ellectra.wsws.OrgType dele=dInitalOrgList.get(i);
            organisationlist pp = new organisationlist();
            if (searchcc.equalsIgnoreCase("1"))
            {
                if(dele.getOrganisationName().equalsIgnoreCase(szsearchname))
                {
                    pp.setOrganizationname(dele.getOrganisationName());
            pp.setId(dele.getId());
            pp.setCountry(dele.getCountry());
            pp.setTaxnumber(dele.getTaxNumber());
            aorg.add(pp);
                }
            }else
            {
            pp.setOrganizationname(dele.getOrganisationName());
            pp.setId(dele.getId());
            pp.setCountry(dele.getCountry());
            pp.setTaxnumber(dele.getTaxNumber());
            aorg.add(pp);
            }
        } 
            try{
          //  Collections.sor
                if (sort.equalsIgnoreCase("0"))
         Collections.sort(aorg, CompareName);
                if (sort.equalsIgnoreCase("1"))
         Collections.sort(aorg, CompareCountry);
                if (sort.equalsIgnoreCase("2"))
         Collections.sort(aorg, CompareTaxNumber);
            }catch (Exception ex) {}
        } catch (Exception ex) {
          organisationlist pp = new organisationlist();
           pp.setOrganizationname("error"+ex.getLocalizedMessage());
           aorg.add(pp);
        }
	
		
	        
    }
    
    private static final Comparator CompareTaxNumber= new Comparator(){
   

        public int compare(Object o1, Object o2) {
             String s1=((organisationlist)o1).getTaxnumber();
        String s2=((organisationlist)o2).getTaxnumber();
        return s1.compareTo(s2);
        }
    };
    
    private static final Comparator CompareName= new Comparator(){
   

        public int compare(Object o1, Object o2) {
             String s1=((organisationlist)o1).getOrganizationname();
        String s2=((organisationlist)o2).getOrganizationname();
        return s1.compareTo(s2);
        }
    };
    
    private static final Comparator CompareCountry= new Comparator(){
   

        public int compare(Object o1, Object o2) {
             String s1=((organisationlist)o1).getCountry();
        String s2=((organisationlist)o2).getCountry();
        return s1.compareTo(s2);
        }
    };
    
    private void LoadOrg()
    {
      
	List <org.ellectra.wsws.OrgType> dInitalOrgList;
        int i;
        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");
            //part1.setId(id);
            
            //call operation
            org.ellectra.wsws.ManageOrgResponse result = port.manageOrgOperation(part1);
            dInitalOrgList=result.getOrganisation();
            
         
        for(i=0;i<dInitalOrgList.size();i++)
        {
            org.ellectra.wsws.OrgType dele=dInitalOrgList.get(i);
            if (id==dele.getId())
            {
            //organisationlist pp = new organisationlist();
            //pp.setOrganizationname(dele.getOrganisationName());
            //pp.setId(dele.getId());
            //pp.setCountry(dele.getCountry());
            //pp.setTaxnumber(dele.getTaxNumber());
            //aorg.add(pp);
            setCountry(dele.getCountry());
            setEmail(dele.getEmail());
            setFax(dele.getFax());
            setId(dele.getId());
            setOrganization(dele.getOrganisationName());
            setOrganizationname(dele.getOrganisationName());
            setPadd(dele.getAddressLine1());
            setPobox(dele.getPostBox());
            setPostcode(dele.getPostCode());
            setTaxnumber(dele.getTaxNumber());
            setTele(dele.getDirectLine());
            setTown(dele.getCityName());
            setUrl(dele.getAuthorityURL());
            }
        }    
            
        } catch (Exception ex) {
           //organisationlist pp = new organisationlist();
           //pp.setOrganizationname("error");
           //aorg.add(pp);
            setOrganization("Error"+ex.getLocalizedMessage());
        }
    }
    
    public String view(/*ActionEvent event*/) {
        organisationlist Selected= (organisationlist) this.getOrgdata().getRowData();
        id=Selected.getId();
        LoadOrg();
        //
        //System.err.println("You have pressed some button: "+Selected.getOrganizationname());
        return "orgview";
    }
    
    public String edit(/*ActionEvent event*/) {
        organisationlist Selected= (organisationlist) this.getOrgdata().getRowData();
        id=Selected.getId();
        LoadOrg();
        //
        //System.err.println("You have pressed some button: "+Selected.getOrganizationname());
        return "orgedit";
    }
    
    public String delete(/*ActionEvent event*/) {
        organisationlist Selected= (organisationlist) this.getOrgdata().getRowData();
//        organisationlist Selected= (organisationlist) this.getOrgdata().getRowData();
        id=Selected.getId();
         LoadOrg();
        //System.err.println("You have pressed some button: "+Selected.getOrganizationname());
        return "orgdelete";
    }
    public String deleteorg()
    {
      try { // Call Web Service Operation
            org.ellectra.wsws.ManageOrgPortType port = service.getManageOrgPort();

            org.ellectra.wsws.ManageOrgRequest part1 = new org.ellectra.wsws.ManageOrgRequest();
            part1.setAction("FR2_Org_Delete");
            part1.setActorSignature("123456");
            //part1.setId(id);
            part1.setOrgId(id);
//            part1.setAddressLine1(getPadd());
//            part1.setAuthorityURL(getUrl());
//            part1.setCityName(getTown());
//            part1.setCountry(getCountry());
//            part1.setDirectLine(getTele());
//            part1.setEmail(getEmail());
//            part1.setFax(getFax());
//            part1.setOrganisationName(getOrganization());
//            part1.setPostBox(getPobox());
//            part1.setPostCode(getPostcode());
//            part1.setTaxNumber(getTaxnumber());
//            part1.setAddressLine2(" ");

            org.ellectra.wsws.ManageOrgResponse result = port.manageOrgOperation(part1);
            //System.out.println("Result = "+result);
            if (result.isReturn()==true)
            {
                return "success";
            }
            else
            {
                return "success";
            }
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            return "error";
        }  
    }
    public String addnew()
    {
         try { // Call Web Service Operation
            org.ellectra.wsws.ManageOrgPortType port = service.getManageOrgPort();

            org.ellectra.wsws.ManageOrgRequest part1 = new org.ellectra.wsws.ManageOrgRequest();
            part1.setAction("FR2_Org_Create");
            part1.setActorSignature("123456");
            //part1.setId(id);
            //part1.setOrgId(id);
            part1.setAddressLine1(getPadd());
            part1.setAuthorityURL(getUrl());
            part1.setCityName(getTown());
            part1.setCountry(getCountry());
            part1.setDirectLine(getTele());
            part1.setEmail(getEmail());
            part1.setFax(getFax());
            part1.setOrganisationName(getOrganization());
            part1.setPostBox(getPobox());
            part1.setPostCode(getPostcode());
            part1.setTaxNumber(getTaxnumber());
            part1.setAddressLine2(" ");
            // TODO process result here
            org.ellectra.wsws.ManageOrgResponse result = port.manageOrgOperation(part1);
            //System.out.println("Result = "+result);
            if (result.isReturn()==true)
            {
                return "success";
            }
            else
            {
                return "success";
            }
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            return "error";
        }
    }
    public String saveedit()
    {
        
        
        try { // Call Web Service Operation
            org.ellectra.wsws.ManageOrgPortType port = service.getManageOrgPort();

            org.ellectra.wsws.ManageOrgRequest part1 = new org.ellectra.wsws.ManageOrgRequest();
            part1.setAction("FR2_Org_Update");
            part1.setActorSignature("123456");
            //part1.setId(id);
            part1.setOrgId(id);
            part1.setAddressLine1(getPadd());
            part1.setAuthorityURL(getUrl());
            part1.setCityName(getTown());
            part1.setCountry(getCountry());
            part1.setDirectLine(getTele());
            part1.setEmail(getEmail());
            part1.setFax(getFax());
            part1.setOrganisationName(getOrganization());
            part1.setPostBox(getPobox());
            part1.setPostCode(getPostcode());
            part1.setTaxNumber(getTaxnumber());
            part1.setAddressLine2(" ");
            // TODO process result here
            org.ellectra.wsws.ManageOrgResponse result = port.manageOrgOperation(part1);
            //System.out.println("Result = "+result);
            if (result.isReturn()==true)
            {
                return "success";
            }
            else
            {
                return "success";
            }
        } catch (Exception ex) {
            // TODO handle custom exceptions here
            return "error";
        }
    }
    
    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 email1 = (String)value;
        if (email1.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 url1 = (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, url1)) {
                    FacesMessage message = new FacesMessage("Invalid URL!");
                    context.addMessage("pinForm", message);
                    throw new ValidatorException(message);
            }
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOrganization() {
        return organization;
    }

    public void setOrganization(String organization) {
        this.organization = organization;
    }

    public String getOrganizationname() {
        return organizationname;
    }

    public void setOrganizationname(String organizationname) {
        this.organizationname = organizationname;
    }

    public String getTaxnumber() {
        return taxnumber;
    }

    public void setTaxnumber(String taxnumber) {
        this.taxnumber = taxnumber;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    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 getPobox() {
        return pobox;
    }

    public void setPobox(String pobox) {
        this.pobox = pobox;
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

    public String getTele() {
        return tele;
    }

    public void setTele(String tele) {
        this.tele = tele;
    }

    public String getFax() {
        return fax;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getSearchcc() {
        return searchcc;
    }

    public void setSearchcc(String searchcc) {
        this.searchcc = searchcc;
    }

    public String getSzsearchname() {
        return szsearchname;
    }

    public void setSzsearchname(String szsearchname) {
        this.szsearchname = szsearchname;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }
}
