package jsonPackage;

import java.io.IOException;
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.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;

import main_package.DataBaseMethodsNaman;

@ManagedBean(name = "myNidhiShareholderCount")
@ViewScoped
public class MyNidhiShareholderCountJson {

    private String json;

    public MyNidhiShareholderCountJson() {

        JSONObject mainObj = new JSONObject();
        JSONArray arr = new JSONArray();
        JSONObject obj = new JSONObject();

        try {
            DataBaseMethodsNaman dbn = new DataBaseMethodsNaman();

            FacesContext context = FacesContext.getCurrentInstance();

            int branchId = -1;

            if (context != null) {
                Map<String, String> params = context.getExternalContext().getRequestParameterMap();

                String branchIdStr = params.get("branchId");

                if (branchIdStr != null && !branchIdStr.trim().isEmpty()) {
                    branchId = Integer.parseInt(branchIdStr);
                }
            }

            dbn.shareholderStatusCount(obj, branchId);

            arr.put(obj);
            mainObj.put("shareholder", arr);

            json = mainObj.toString();

        } catch (Exception e) {
            e.printStackTrace();

            JSONObject error = new JSONObject();
            error.put("error", "Unable to generate JSON");

            json = error.toString();
        }
    }

    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);
        externalContext.getResponseOutputWriter().flush();

        facesContext.responseComplete();
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }
}