package json_package;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import main_package.DataBaseConnection;
import main_package.DataBaseMethods;
import main_package.DataBaseMethodsSalary;
import main_package.EmpInfo;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ManagedBean(name="centerListJson")
@ViewScoped
public class CenterListJsonBean implements Serializable
{
	String json;
	DataBaseMethods obj=new DataBaseMethods();
	ArrayList<EmpInfo> list;
	Date searchDate;
	
	public CenterListJsonBean() throws ParseException 
	{
		Map<String, String> params =FacesContext.getCurrentInstance().
                getExternalContext().getRequestParameterMap();
		
		String sDate=params.get("searchDate");
		String userId=params.get("userId");
		String branchStr = params.get("branchId");
		int branchId = Integer.valueOf(branchStr);
		
		 if(userId.contains("'") || sDate.contains("'"))
			{
				userId="";
				sDate="";
			}
		
		DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		if(sDate!=null && !sDate.equals(""))
		{
			searchDate = (Date)formatter.parse(sDate);
		}
		
		
       Connection conn=DataBaseConnection.JAVAConnection();
		ArrayList<SelectItem> employeeList=obj.centerListForUpcomingEMIForApp(branchId,searchDate, searchDate);
		
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		JSONObject mainobj = new JSONObject();
		JSONArray arr=new JSONArray();
		
		if(employeeList.size()>0)
	     {
	    	 for(SelectItem uu : employeeList)
			   {
				   JSONObject obj = new JSONObject();
				   
				 
				   obj.put("centerLabel",uu.getLabel());
				   obj.put("centerValue", uu.getValue());
				   
				   arr.add(obj);
			   }
	     }

	    mainobj.put("track", arr);

	json=mainobj.toJSONString();
	
		//int i=new DatabaseMethods1().news(concern);
		  
	}
	
	
	
	public void renderJson() throws IOException {
 	    FacesContext facesContext = FacesContext.getCurrentInstance();
 	    ExternalContext externalContext = facesContext.getExternalContext();
 	    externalContext.setResponseContentType("application/json");
 	    externalContext.setResponseCharacterEncoding("UTF-8");
 	    externalContext.getResponseOutputWriter().write(json);
 	    facesContext.responseComplete();
 	    
 	    
 	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}
}
