package json_package;

import java.io.IOException;
import java.io.Serializable;
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 main_package.DataBaseMethods;
import main_package.EmpInfo;
import main_package.UserInfo;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ManagedBean(name="viewGpsTrackingJson")
@ViewScoped
public class ViewGpsTrackingJsonBean implements Serializable
{
	String json;
	Date searchDate;
	
	public ViewGpsTrackingJsonBean() throws ParseException 
	{
		Map<String, String> params =FacesContext.getCurrentInstance().
                getExternalContext().getRequestParameterMap();
       
        
	
		String empUserId=params.get("empUserId");
		String searchDt=params.get("searchDate");
		if(empUserId.contains("'") || searchDt.contains("'"))
		{
			empUserId="";
			searchDt="";
		}
		
		ArrayList<EmpInfo> list=new ArrayList<>();
		
		DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		if(searchDt!=null && !searchDt.equals(""))
		{
			searchDate = (Date)formatter.parse(searchDt);
		}
		
		list=new DataBaseMethods().gpsTrackingListByEmpUserId(empUserId, searchDate);
     
     
		JSONObject mainobj = new JSONObject();
		JSONArray arr=new JSONArray();
			
		if(list.size()>0)
	     {
	    	 for(EmpInfo uu : list)
			   {
				   JSONObject obj = new JSONObject();
				   
				   obj.put("sno",uu.getSno());
				   obj.put("strTrackingDate",uu.getStrTrackingDate());
				   obj.put("latitude",uu.getLatitude());
				   obj.put("longitude",uu.getLongitude());
				   
				   arr.add(obj);
			   }
				
	     }

	    mainobj.put("track", arr);

		json=mainobj.toJSONString();
	}
	
	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;
	}
}
