package jsonPackage;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
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.DataBaseMethodTaheer;
import main_package.LoanInfo;

@ManagedBean(name = "myNidhiActiveLoanList")
@ViewScoped

public class MyNidhiActiveLoanListByLoanTypeJson
{
    private String json;

    DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();

    
    
    public MyNidhiActiveLoanListByLoanTypeJson()
    {
        JSONObject mainobj = new JSONObject();
        JSONArray mainArray = new JSONArray();

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

        String branchId = params.get("branchId");
        String dsacode = params.get("dsacode");
        String loanType = params.get("loanType");
        String frequency = params.get("frequency");

        if (branchId == null || branchId.trim().isEmpty())
        {
            branchId = "-1";
        }

        if (dsacode == null || dsacode.trim().isEmpty())
        {
            dsacode = "all";
        }

        if (frequency == null || frequency.trim().isEmpty())
        {
            frequency = "all";
        }

        Connection conn = null;

        try
        {
            if (loanType == null)
            {
                throw new IllegalArgumentException("Invalid loanType");
            }

            conn = DataBaseConnection.JAVAConnection();

            if (conn == null)
            {
                throw new Exception("Database connection failed");
            }

            ArrayList<LoanInfo> list = dbmt.activeLoanListByLoanType(Integer.parseInt(branchId), loanType, conn, frequency, 
            														 dsacode);
            System.out.println(list.size());

            for (LoanInfo info : list)
            {
                JSONObject obj = new JSONObject();
                
                obj.put("loanNo", info.getLoanNo());
                obj.put("shareHolderNo", info.getShareHolderNo());
                obj.put("applicantName", info.getApplicantName());
                obj.put("fatherHusbandName", info.getFatherHusbandName());
                obj.put("contactNo", info.getContactNo());
                obj.put("id", info.getId());
                obj.put("loanAmount", info.getLoanAmount());
                obj.put("interestAmount", info.getInterestAmount());
                obj.put("approvalDate", info.getApprovalDate() == null ? null : info.getApprovalDate().toString());
                obj.put("strApprovalDate", info.getStrApprovalDate());

                mainArray.add(obj);
            }

            mainobj.put("status", "success");
            mainobj.put("loanList", mainArray);
            mainobj.put("count", mainArray.size());
        }
        catch (Exception e)
        {
            e.printStackTrace();

            mainobj.put("status", "error");
            mainobj.put("message", e.getMessage() == null ? "Unable to fetch active loans" : e.getMessage());
        }
        
        finally
        {
            if (conn != null)
            {
                try
                {
                    conn.close();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }

        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;
    }
}