package json_package;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
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.EmpInfo;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ManagedBean(name="centerSelectItemListJson")
@ViewScoped
public class CenterSelectItemListJson implements Serializable
{
	String json;
	DataBaseMethods db=new DataBaseMethods();
	ArrayList<EmpInfo> list;
	Date searchDate;
	ArrayList<SelectItem> centerList;
	
	
	public CenterSelectItemListJson() throws ParseException 
	{
		Map<String, String> params =FacesContext.getCurrentInstance().
                getExternalContext().getRequestParameterMap();
		
		String userId=params.get("userId");
		String branchId=params.get("branchId");
		
		if(userId.contains("'"))
		{
			userId="";
		}
		
       Connection conn=DataBaseConnection.JAVAConnection();
       String userType=db.userTypeByUserId(userId, conn);
       if(userType.equalsIgnoreCase("admin"))
       {
    	   centerList=db.allcenter(Integer.parseInt(branchId),"all",conn);
       }
       else
       {
    	    String dsaCode=db.dsaCodeByEmpUserId(userId, conn);
    	    centerList=db.allcenter(Integer.parseInt(branchId), dsaCode,conn);
       }
   
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		JSONObject mainobj = new JSONObject();
		JSONArray arr=new JSONArray();
		
		if(centerList.size()>0)
	     {
	    	 for(SelectItem uu : centerList)
			   {
				   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;
	}
	
}	