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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ViewScoped
@ManagedBean(name="dsaListJson")
public class DsaListJson implements Serializable
{
	String json;
	Date startDate, endDate;
	DataBaseMethods db=new DataBaseMethods();
	ArrayList<SelectItem> dsaList;
	
	public DsaListJson() 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();
		
		dsaList=db.allDsaList(Integer.parseInt(branchId),"Loan",conn);
		
		
		
		JSONObject mainobj = new JSONObject();
		JSONArray arr=new JSONArray();
		
		String userType=db.userTypeByUserId(userId, conn);
		if(userType.equals("admin") || userType.equals("masterAdmin"))
		{
			if(dsaList.size()>0)
		     {
		    	 for(SelectItem uu : dsaList)
				   {
					   JSONObject obj = new JSONObject();
					   
					 
					   obj.put("dsaLabel",uu.getLabel());
					   obj.put("dsaValue", uu.getValue());
					   
					   arr.add(obj);
				   }
		     }
		}
		else
		{
			  JSONObject obj = new JSONObject();
			  
			   String dsaCode=db.dsaCodeByEmpUserId(userId, conn);
			   obj.put("dsaValue", dsaCode);
			   obj.put("dsaLabel", db.dsaNameById(dsaCode, conn));
			   
			   
			   arr.add(obj);
		}
		
		

	    mainobj.put("track", arr);

	json=mainobj.toJSONString();
	
		//int i=new DatabaseMethods1().news(concern);
	try {
		conn.close();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}
	
	
	
	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;
	}
}
