package main_package;

import java.io.Serializable;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

@ManagedBean(name="addEmpBranch")
@ViewScoped

public class AddEmployeeBranchBean implements Serializable 
{
	String empId;
	String[] branchId;
	List<SelectItem> empList = new ArrayList<SelectItem>();
	List<SelectItem> branchList;
	DataBaseMethods dbObj = new DataBaseMethods(); 
	boolean renVal=false;
	
	public AddEmployeeBranchBean()
	{
		empId="-1";
		Connection con = DataBaseConnection.JAVAConnection();
		empList = dbObj.employeeListAll(con);
		
		try {
			con.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void updateBranch()
	{
		if(empId.equals("-1"))
		{
			renVal=false;
		}
		else
		{
			Connection con = DataBaseConnection.JAVAConnection();
			branchList= new ArrayList<SelectItem>(); 
	        branchList = dbObj.branchListAllWithName(empId,con);
	        if(branchList.size()==0)
	        {
	        	renVal=false;
	        	FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("All branchs already alocate to this employee"));
	        }
	        else
	        {
	        	renVal=true;	
	        }
			

			try {
				con.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
	}
	
	public String addBranch()
	{
		if(branchId.length>0)
		{
			Connection con = DataBaseConnection.JAVAConnection();
			for(int i=0;i<branchId.length;i++)
			{
				dbObj.insertBranchEmp(empId, Integer.valueOf(branchId[i]), con);
			}
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Employee added to Branchs Sucesfully"));
			
			try {
				con.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			return "addEmployeeBranch";
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Select one branch atleast"));
			return "";
		}
	}
	
	
	public String getEmpId() {
		return empId;
	}

	public void setEmpId(String empId) {
		this.empId = empId;
	}

	public List<SelectItem> getEmpList() {
		return empList;
	}

	public void setEmpList(List<SelectItem> empList) {
		this.empList = empList;
	}

	public boolean isRenVal() {
		return renVal;
	}

	public void setRenVal(boolean renVal) {
		this.renVal = renVal;
	}

	public String[] getBranchId() {
		return branchId;
	}

	public void setBranchId(String[] branchId) {
		this.branchId = branchId;
	}

	public List<SelectItem> getBranchList() {
		return branchList;
	}

	public void setBranchList(List<SelectItem> branchList) {
		this.branchList = branchList;
	}
	
}
