
package jsonPackage;

import java.io.IOException;
import java.sql.Connection;
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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import main_package.DataBaseConnection;
import main_package.DataBaseMethodsRavi;

@ManagedBean(name = "empAttendanceGetJsonBean")
@ViewScoped
public class EmpAttendanceGetJsonBean {

	String json;
	DataBaseMethodsRavi dbr = new DataBaseMethodsRavi();

	public EmpAttendanceGetJsonBean() {

		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

		String userId = params.get("userId");

		if (userId == null || userId.trim().isEmpty()) {

			JSONObject error = new JSONObject();
			error.put("status", "error");
			error.put("message", "userId is required");

			json = error.toJSONString();
			return;
		}

		Connection conn = null;

		try {
			conn = DataBaseConnection.JAVAConnection();

			JSONArray attendance = dbr.todayAttendanceByUserId(userId, conn);

			JSONObject response = new JSONObject();
			if (attendance.isEmpty()) {
			    response.put("status", "error");
			    response.put("message", "Attendance data not found");
			    response.put("userId", userId);
			} else {
			    response.put("status", "success");
			    response.put("message", "Attendance data found");
			    response.put("userId", userId);
			    response.put("data", attendance);
			}

			json = response.toJSONString();

		} catch (Exception e) {

			e.printStackTrace();

			JSONObject error = new JSONObject();
			error.put("status", "error");
			error.put("message", "Unable to get attendance data");

			json = error.toJSONString();

		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				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;
	}
}
