/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JsonGraphs.Util;

import JsonGraphs.Controller.barChartData;
import Controller.Generate_100_Random_Colors;
import JsonGraphs.Bean.BucketWiseLoanOutstandingBean;
import JsonGraphs.Util.JsonDbHandler;
import JsonGraphs.Controller.datasets;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import oracle.jdbc.OracleTypes;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonDbHandler {

    ResultSet rs = null;
    ResultSet resultset = null;
    CallableStatement proc = null;
    Connection connection = null;
    Statement statement = null;

    public barChartData getGraphData(String toDate, String fromDate, String distCode, String reportSelection) {

        barChartData barChartDataObjOut = null;
        ArrayList<String> labels = null;
        ArrayList<datasets> datasets = null;
        datasets datasetsObj = null;
        ArrayList<Integer> data = null;
        ArrayList<String> randColors = null;
        String color = null;


//        if (distCode == "") {
//            distCode = "null";
//        }

        int i = 0;
        randColors = new Generate_100_Random_Colors().genRandColors();
        barChartDataObjOut = new barChartData();
        barChartDataObjOut.setHeader("LOAN OUTSTANDING BUCKETWISE");
        labels = new ArrayList<String>();
        labels.add("0-3 Months");
        labels.add("3-6 Months");
        labels.add("Greater than 6 Months");
        barChartDataObjOut.setLabels(labels);


        try {
            connection = LoginDb.DbHandler.getDBConnection();
            proc = connection.prepareCall("{ ?=call Dashboard_Query(?,?,?,?) }");
        
            datasets = new ArrayList<datasets>();

            proc.registerOutParameter(1, OracleTypes.CURSOR);
            proc.setString(2, fromDate);
            proc.setString(3, toDate);
            proc.setString(4, distCode);
            proc.setString(5, reportSelection);

            proc.executeUpdate();

            rs = (ResultSet) proc.getObject(1);

            int k = 0;
            while (rs.next()) {
                if (i % 3 == 0) {
                    datasetsObj = new datasets();
                    color = randColors.get(k++);
                    datasetsObj.setLabel(rs.getString(1));
                    datasetsObj.setBackgroundColor(color);
                    data = new ArrayList<Integer>();
                    data.add(rs.getInt(2));
                } else if (i % 3 == 2) {
                    data.add(rs.getInt(2));
                    datasetsObj.setData(data);
                    datasets.add(datasetsObj);
                } else {
                    data.add(rs.getInt(2));
                }
                i++;
            }
            barChartDataObjOut.setDatasets(datasets);


        } catch (Exception ex) {
            System.out.println("Error Occurred during processing.");
        } finally {
            try {
                proc.close();
            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }
            try {
                connection.close();
            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during connection close.");
            }
            try {
                rs.close();
            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }
           // return barChartDataObjOut;
        }
        return barChartDataObjOut;

    }

    // For CROP-WISE SNAPSHOT OF LOANS
    public barChartData getGraphData1(String toDate, String fromDate, String distCode, String reportSelection) {

        barChartData barChartDataObjOut = null;
        ArrayList<String> labels = null;
        ArrayList<datasets> datasets = null;
        datasets datasetsObj = null;
        ArrayList<Integer> data = null;
        ArrayList<String> randColors = null;
        String color = null;
        String query;

        int i = 0;
        randColors = new Generate_100_Random_Colors().genRandColors();
        barChartDataObjOut = new barChartData();
        barChartDataObjOut.setHeader("CROP-WISE SNAPSHOT OF LOANS");

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            statement = connection.createStatement();

            
            if (!(distCode.equalsIgnoreCase(""))) {
                resultset = statement.executeQuery("select distinct q.loan_date from (select p.intt_cat_desc as Crop_Name,to_char(da.acct_open_dt,'YYYY') as Loan_Date,count(*) as No_Of_Loans from dep_account da,dep_product p,kyc_details kd,pacs_master pm, (select distinct dccb_code,dccb_name from  dccb_br_map) m where da.dep_prod_id=p.id and da.curr_status IN ('O','C')  and da.pacs_id=pm.pacs_id  and kd.cif_no=da.customer_no and pm.dccb_code=m.dccb_code and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy') and  to_date('" + toDate + "','dd/mm/yyyy') and m.dccb_code='" + distCode + "' group by to_char(da.acct_open_dt,'YYYY'),p.intt_cat_desc order by p.intt_cat_desc, to_char(da.acct_open_dt,'YYYY')) q order by 1");
            } else {
                resultset = statement.executeQuery("select distinct q.loan_date from (select p.intt_cat_desc as Crop_Name,to_char(da.acct_open_dt,'YYYY') as Loan_Date,count(*) as No_Of_Loans from dep_account da,dep_product p,kyc_details kd,pacs_master pm, (select distinct dccb_code,dccb_name from  dccb_br_map) m where da.dep_prod_id=p.id and da.curr_status IN ('O','C')  and da.pacs_id=pm.pacs_id  and kd.cif_no=da.customer_no and pm.dccb_code=m.dccb_code and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy') and  to_date('" + toDate + "','dd/mm/yyyy') group by to_char(da.acct_open_dt,'YYYY'),p.intt_cat_desc order by p.intt_cat_desc, to_char(da.acct_open_dt,'YYYY')) q order by 1");
            }
            labels = new ArrayList<String>();
            while (resultset.next()) {
                labels.add(resultset.getString(1));
            }


            barChartDataObjOut.setLabels(labels);
        
        } catch (SQLException ex) {
            System.out.println("Error Occurred during processing.");
        } finally {
            try {
                statement.close();
                connection.close();
                resultset.close();
            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during connection close.");
            }

        }

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            proc = connection.prepareCall("{ ?=call Dashboard_Query(?,?,?,?) }");
        } catch (SQLException ex) {
           // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } finally {
            try {
                datasets = new ArrayList<datasets>();

                proc.registerOutParameter(1, OracleTypes.CURSOR);
                proc.setString(2, fromDate);
                proc.setString(3, toDate);
                proc.setString(4, distCode);
                proc.setString(5, reportSelection);

                proc.executeUpdate();

                rs = (ResultSet) proc.getObject(1);


                int k = 0;
                String x = "";
                rs.next();
                while (true) {

                    if (i % labels.size() == 0) {
                        datasetsObj = new datasets();
                        color = randColors.get(k++);
                        x = rs.getString(1);
                        datasetsObj.setLabel(x);
                        datasetsObj.setBackgroundColor(color);
                        data = new ArrayList<Integer>();

                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            rs.next();
                        } else {

                            data.add(0);
                        }
                    } else if (i % labels.size() == labels.size() - 1) {
                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            if (rs.next() == false) {
                                datasetsObj.setData(data);
                                datasets.add(datasetsObj);
                                i = -1;
                                break;
                            }
                        } else {
                            data.add(0);
                        }
                        datasetsObj.setData(data);
                        datasets.add(datasetsObj);
                        i = -1;



                    } else {
                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            rs.next();
                        } else {
                            data.add(0);
                        }
                    }
                    i++;
                    String y = rs.getString(2);
                    String z = rs.getString(1);
                }
                barChartDataObjOut.setDatasets(datasets);

            } catch (Exception ex) {
                System.out.println("Error Occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }
                
                try {
                    rs.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }
               // return barChartDataObjOut;
            } 
            try {
                    connection.close();
                } catch (SQLException ex) {
                   System.out.println("Error Occurred during connection close.");
                }
        }
        return barChartDataObjOut;
    }

    //For CROP-WISE LOAN DEMAND
    public barChartData getGraphData3(String toDate, String fromDate, String distCode, String reportSelection) {

        barChartData barChartDataObjOut = null;
        ArrayList<String> labels = null;
        ArrayList<datasets> datasets = null;
        datasets datasetsObj = null;
        ArrayList<Integer> data = null;
        ArrayList<String> randColors = null;
        String color = null;

        String query;

        int i = 0;
        randColors = new Generate_100_Random_Colors().genRandColors();
        barChartDataObjOut = new barChartData();
        barChartDataObjOut.setHeader("CROP-WISE LOAN DEMAND");

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            statement = connection.createStatement();
        
            if (!(distCode.equalsIgnoreCase(""))) {
                resultset = statement.executeQuery("select distinct q.loan_date from (select p.intt_cat_desc as Crop_Name,to_char(da.acct_open_dt,'YYYY') as Loan_Date,count(*) as No_Of_Loans from dep_account da,dep_product p,kyc_details kd,pacs_master pm, (select distinct dccb_code,dccb_name from  dccb_br_map) m where da.dep_prod_id=p.id and da.curr_status='O'  and da.pacs_id=pm.pacs_id  and kd.cif_no=da.customer_no and pm.dccb_code=m.dccb_code and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy') and  to_date('" + toDate + "','dd/mm/yyyy') and m.dccb_code='" + distCode + "' group by to_char(da.acct_open_dt,'YYYY'),p.intt_cat_desc order by  p.intt_cat_desc,to_char(da.acct_open_dt,'YYYY')) q order by 1");
            } else {
                resultset = statement.executeQuery("select distinct q.loan_date from (select p.intt_cat_desc as Crop_Name,to_char(da.acct_open_dt,'YYYY') as Loan_Date,count(*) as No_Of_Loans from dep_account da,dep_product p,kyc_details kd,pacs_master pm, (select distinct dccb_code,dccb_name from  dccb_br_map) m where da.dep_prod_id=p.id and da.curr_status='O'  and da.pacs_id=pm.pacs_id  and kd.cif_no=da.customer_no and pm.dccb_code=m.dccb_code and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy') and  to_date('" + toDate + "','dd/mm/yyyy') group by to_char(da.acct_open_dt,'YYYY'),p.intt_cat_desc order by p.intt_cat_desc,to_char(da.acct_open_dt,'YYYY')) q order by 1");
            }
            labels = new ArrayList<String>();
            while (resultset.next()) {
                labels.add(resultset.getString(1));
            }

            barChartDataObjOut.setLabels(labels);
        } catch (SQLException ex) {
            System.out.println("Error Occurred during processing.");
        } finally {
            try {
                statement.close();
                connection.close();
                resultset.close();
            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during connection close.");
            }
        }

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            proc = connection.prepareCall("{ ?=call Dashboard_Query(?,?,?,?) }");
        } catch (SQLException ex) {
           // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } finally {
            try {
                datasets = new ArrayList<datasets>();

                proc.registerOutParameter(1, OracleTypes.CURSOR);
                proc.setString(2, fromDate);
                proc.setString(3, toDate);
                proc.setString(4, distCode);
                proc.setString(5, reportSelection);

                proc.executeUpdate();

                rs = (ResultSet) proc.getObject(1);

                int k = 0;
                String x = "";
                rs.next();
                while (true) {

                    if (i % labels.size() == 0) {
                        datasetsObj = new datasets();
                        color = randColors.get(k++);
                        x = rs.getString(1);
                        datasetsObj.setLabel(x);
                        datasetsObj.setBackgroundColor(color);
                        data = new ArrayList<Integer>();

                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            rs.next();
                        } else {

                            data.add(0);
                        }
                    } else if (i % labels.size() == labels.size() - 1) {
                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            if (rs.next() == false) {
                                datasetsObj.setData(data);
                                datasets.add(datasetsObj);
                                i = -1;
                                break;
                            }
                        } else {
                            data.add(0);
                        }
                        datasetsObj.setData(data);
                        datasets.add(datasetsObj);
                        i = -1;



                    } else {
                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            rs.next();
                        } else {
                            data.add(0);
                        }
                    }
                    i++;
                    String y = rs.getString(2);
                    String z = rs.getString(1);
                }
                barChartDataObjOut.setDatasets(datasets);

            } catch (Exception ex) {
                System.out.println("Error Occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }
                
                try {
                    rs.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }
               // return barChartDataObjOut;
            } 
            try {
                    connection.close();
                } catch (SQLException ex) {
                   System.out.println("Error Occurred during connection close.");
                }
        }
        return barChartDataObjOut;
    }

    public barChartData getGraphData4(String toDate, String fromDate, String distCode, String reportSelection) {

        barChartData barChartDataObjOut = null;
        ArrayList<String> labels = null;
        ArrayList<datasets> datasets = null;
        datasets datasetsObj = null;
        ArrayList<Integer> data = null;
        ArrayList<String> randColors = null;
        String color = null;

        int i = 0;
        randColors = new Generate_100_Random_Colors().genRandColors();
        barChartDataObjOut = new barChartData();
        barChartDataObjOut.setHeader("CROP-WISE LOAN RECOVERY");

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            statement = connection.createStatement();
        
            if (!(distCode.equalsIgnoreCase(""))) {
                resultset = statement.executeQuery("select distinct q.loan_date from (select p.intt_cat_desc Crop_Name,to_char(da.acct_open_dt,'YYYY') Loan_Date,count(*) No_Of_Loans from dep_account da,dep_product p,kyc_details kd,pacs_master pm, (select distinct dccb_code,dccb_name from  dccb_br_map) m where da.dep_prod_id=p.id and da.curr_status='C'  and da.pacs_id=pm.pacs_id  and kd.cif_no=da.customer_no and pm.dccb_code=m.dccb_code and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy') and  to_date('" + toDate + "','dd/mm/yyyy') and  m.dccb_code='" + distCode + "' group by to_char(da.acct_open_dt,'YYYY'),p.intt_cat_desc order by p.intt_cat_desc,to_char(da.acct_open_dt,'YYYY')) q order by 1");
            } else {
                resultset = statement.executeQuery("select distinct q.loan_date from (select p.intt_cat_desc Crop_Name,to_char(da.acct_open_dt,'YYYY') Loan_Date,count(*) No_Of_Loans from dep_account da,dep_product p,kyc_details kd,pacs_master pm, (select distinct dccb_code,dccb_name from  dccb_br_map) m where da.dep_prod_id=p.id and da.curr_status='C'  and da.pacs_id=pm.pacs_id  and kd.cif_no=da.customer_no and pm.dccb_code=m.dccb_code and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy') and  to_date('" + toDate + "','dd/mm/yyyy') group by to_char(da.acct_open_dt,'YYYY'),p.intt_cat_desc order by p.intt_cat_desc,to_char(da.acct_open_dt,'YYYY')) q order by 1");
            }
            labels = new ArrayList<String>();
            while (resultset.next()) {
                labels.add(resultset.getString(1));
            }


            barChartDataObjOut.setLabels(labels);
        } catch (SQLException ex) {
            System.out.println("Error Occurred during processing.");
        
        } finally {
            try {
                statement.close();
                connection.close();
                resultset.close();

            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during connection close.");
            }

        }

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            proc = connection.prepareCall("{ ?=call Dashboard_Query(?,?,?,?) }");
        } catch (SQLException ex) {
           // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } finally {
            try {
                datasets = new ArrayList<datasets>();

                proc.registerOutParameter(1, OracleTypes.CURSOR);
                proc.setString(2, fromDate);
                proc.setString(3, toDate);
                proc.setString(4, distCode);
                proc.setString(5, reportSelection);

                proc.executeUpdate();

                rs = (ResultSet) proc.getObject(1);
                int k = 0;
                String x = "";
                rs.next();

                while (true) {

                    if (i % labels.size() == 0) {
                        datasetsObj = new datasets();
                        color = randColors.get(k++);
                        x = rs.getString(1);
                        datasetsObj.setLabel(x);
                        datasetsObj.setBackgroundColor(color);
                        data = new ArrayList<Integer>();

                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            rs.next();
                        } else {

                            data.add(0);
                        }
                    } else if (i % labels.size() == labels.size() - 1) {
                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            if (rs.next() == false) {
                                datasetsObj.setData(data);
                                datasets.add(datasetsObj);
                                i = -1;
                                break;
                            }
                        } else {
                            data.add(0);
                        }
                        datasetsObj.setData(data);
                        datasets.add(datasetsObj);
                        i = -1;



                    } else {
                        if ((rs.getString(2).equalsIgnoreCase(labels.get(i))) && (x.equalsIgnoreCase(rs.getString(1)))) {
                            data.add(rs.getInt(3));
                            rs.next();
                        } else {
                            data.add(0);
                        }
                    }
                    i++;
                    String y = rs.getString(2);
                    String z = rs.getString(1);
                }
                barChartDataObjOut.setDatasets(datasets);

            } catch (Exception ex) {
                System.out.println("Error Occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during proc close.");
                }                
                try {
                    rs.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }
               // return barChartDataObjOut;
            }
            try {
                    connection.close();
            } catch (SQLException ex) {
                   System.out.println("Error Occurred during connection close.");
                }
        }
        return barChartDataObjOut;
    }

    public barChartData getGraphData2(String toDate, String fromDate, String distCode, String reportSelection) {

        barChartData barChartDataObjOut = null;
        ArrayList<String> labels = null;
        ArrayList<datasets> datasets = null;
        datasets datasetsObj = null;
        ArrayList<Integer> data = null;
        ArrayList<String> randColors = null;
        String color = null;


        int i = 0;
        randColors = new Generate_100_Random_Colors().genRandColors();
        barChartDataObjOut = new barChartData();
        barChartDataObjOut.setHeader("LOAN OUTSTANDING vs LOAN RECOVERED");

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            statement = connection.createStatement();
        
            if (!(distCode.equalsIgnoreCase(""))) {
                resultset = statement.executeQuery("select distinct intt_cat_desc from (select dp.intt_cat_desc, sum(case da.curr_status when 'O' then 1 else 0 end) loan_outst, sum(case da.curr_status when 'C' then 1 else 0 end) loan_rec, decode(da.curr_status,'O','Loan Outstanding','Loan Recovered') as status, 0 as total_loan, count(*) as loan_count from dep_account da, dep_product dp,pacs_master pm where dp.id=da.dep_prod_id and pm.pacs_id=da.pacs_id  and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy')  and  to_date('" + toDate + "','dd/mm/yyyy') and case when " + distCode + " is not null then case when pm.dccb_code=" + distCode + "  then 1 else 0 end else 1  end=1 group by dp.intt_cat_desc,da.curr_status union all select dp.intt_cat_desc, 0,0,'Loan Disbursed',count(*),count(*) as loan_count from dep_account da, dep_product dp,pacs_master pm where dp.id=da.dep_prod_id and pm.pacs_id=da.pacs_id  and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy')  and  to_date('" + toDate + "','dd/mm/yyyy') and case when " + distCode + " is not null then case when pm.dccb_code=" + distCode + "  then 1 else 0 end else 1  end=1 group by dp.intt_cat_desc) order by 1");
            } else {
                resultset = statement.executeQuery("select distinct intt_cat_desc from (select dp.intt_cat_desc, sum(case da.curr_status when 'O' then 1 else 0 end) loan_outst, sum(case da.curr_status when 'C' then 1 else 0 end) loan_rec, decode(da.curr_status,'O','Loan Outstanding','Loan Recovered') as status, 0 as total_loan, count(*) as loan_count from dep_account da, dep_product dp,pacs_master pm where dp.id=da.dep_prod_id and pm.pacs_id=da.pacs_id  and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy')  and  to_date('" + toDate + "','dd/mm/yyyy')  group by dp.intt_cat_desc,da.curr_status union all select dp.intt_cat_desc, 0,0,'Loan Disbursed',count(*),count(*) as loan_count from dep_account da, dep_product dp,pacs_master pm where dp.id=da.dep_prod_id and pm.pacs_id=da.pacs_id  and da.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy')  and  to_date('" + toDate + "','dd/mm/yyyy') group by dp.intt_cat_desc) order by 1");
            }
            labels = new ArrayList<String>();
            while (resultset.next()) {
                labels.add(resultset.getString(1));
            }


            barChartDataObjOut.setLabels(labels);
        } catch (SQLException ex) {
            System.out.println("Error Occurred during processing.");
        } finally {
            try {
                statement.close();
                connection.close();
                resultset.close();

            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during connection close.");
            }

        }

        try {
            connection = LoginDb.DbHandler.getDBConnection();
            proc = connection.prepareCall("{ ?=call Dashboard_Query(?,?,?,?) }");
        } catch (SQLException ex) {
           // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } finally {
            try {
                datasets = new ArrayList<datasets>();

                proc.registerOutParameter(1, OracleTypes.CURSOR);
                proc.setString(2, fromDate);
                proc.setString(3, toDate);
                proc.setString(4, distCode);
                proc.setString(5, reportSelection);

                proc.executeUpdate();

                rs = (ResultSet) proc.getObject(1);

                int k = 0;
                String x = "";
                rs.next();
                for (i = 0; i < labels.size() * 3; i++) {

                    if (i % labels.size() == 0) {
                        datasetsObj = new datasets();
                        color = randColors.get(k++);
                        x = rs.getString(4);
                        datasetsObj.setLabel(x);
                        datasetsObj.setBackgroundColor(color);
                        data = new ArrayList<Integer>();

                        if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Disbursed"))) {
                            data.add(rs.getInt(5));
                            rs.next();
                        } else if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Outstanding"))) {
                            data.add(rs.getInt(2));
                            rs.next();
                        } else {
                            if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Recovered"))) {

                                data.add(rs.getInt(3));
                                rs.next();
                            } else {
                                data.add(0);
                            }
                        }
                    } else if (i % labels.size() == labels.size() - 1) {
                        if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Disbursed"))) {
                            data.add(rs.getInt(5));
                            rs.next();
                        } else if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Outstanding"))) {
                            data.add(rs.getInt(2));
                            rs.next();
                        } else {
                            if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Recovered"))) {

                                data.add(rs.getInt(3));
                                rs.next();
                            } else {
                                data.add(0);
                            }
                        }
                        datasetsObj.setData(data);
                        datasets.add(datasetsObj);




                    } else {
                        if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Disbursed"))) {
                            data.add(rs.getInt(5));
                            rs.next();
                        } else if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Outstanding"))) {
                            data.add(rs.getInt(2));
                            rs.next();
                        } else {
                            if ((rs.getString(1).equalsIgnoreCase(labels.get(i % labels.size()))) && (x.equalsIgnoreCase("Loan Recovered"))) {

                                data.add(rs.getInt(3));
                                rs.next();
                            } else {
                                data.add(0);
                            }
                        }
                    }


                }
                barChartDataObjOut.setDatasets(datasets);

            } catch (Exception ex) {
                System.out.println("Error Occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }                
                try {
                    rs.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }
               // return barChartDataObjOut;
            }
            try {
                   connection.close();
                } catch (SQLException ex) {
                   System.out.println("Error Occurred during connection close.");
                }
        }
        return barChartDataObjOut;
    }

    public barChartData getGraphData5(String toDate, String fromDate, String distCode, String reportSelection) {

        barChartData barChartDataObjOut = null;
        ArrayList<String> labels = null;
        ArrayList<datasets> datasets = null;
        datasets datasetsObj1 = null;
        datasets datasetsObj2 = null;
        ArrayList<Integer> data1 = null;
        ArrayList<Integer> data2 = null;
        ArrayList<String> randColors = null;
        String color = null;


        int i = 0;
        randColors = new Generate_100_Random_Colors().genRandColors();
        barChartDataObjOut = new barChartData();
        barChartDataObjOut.setHeader("DCCB LOAN OUTSTANDING vs LOAN RECOVERED");


        try {
            connection = LoginDb.DbHandler.getDBConnection();
            statement = connection.createStatement();
        
            if (!(distCode.equalsIgnoreCase(""))) {
                resultset = statement.executeQuery("select dccb_name from (select  distinct m.dccb_name,  SUM(CASE WHEN d.curr_status='C'  and d.prin_outst=0 THEN 1 ELSE 0  END)   LOAN_Recovered,   SUM(CASE WHEN d.curr_status='O'  and d.prin_outst<>0 THEN 1 ELSE 0  END)   LOAN_Outstanding  from dep_account d,dep_product dd,kyc_details kd,pacs_master pm,  (select distinct dccb_code,dccb_name from  dccb_br_map) m  where d.dep_prod_id=dd.id and kd.cif_no=d.customer_no  and d.pacs_id=pm.pacs_id and pm.dccb_code=m.dccb_code and d.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy')  and  to_date('" + toDate + "','dd/mm/yyyy') and case when " + distCode + " is not null then case when m.dccb_code=" + distCode + "  then 1 else 0 end else 1  end=1  GROUP BY m.dccb_name order by m.dccb_name) n");
            } else {
                resultset = statement.executeQuery("select dccb_name from (select  distinct m.dccb_name,  SUM(CASE WHEN d.curr_status='C'  and d.prin_outst=0 THEN 1 ELSE 0  END)   LOAN_Recovered,   SUM(CASE WHEN d.curr_status='O'  and d.prin_outst<>0 THEN 1 ELSE 0  END)   LOAN_Outstanding  from dep_account d,dep_product dd,kyc_details kd,pacs_master pm,  (select distinct dccb_code,dccb_name from  dccb_br_map) m  where d.dep_prod_id=dd.id and kd.cif_no=d.customer_no  and d.pacs_id=pm.pacs_id and pm.dccb_code=m.dccb_code and d.acct_open_dt between to_date('" + fromDate + "','dd/mm/yyyy')  and  to_date('" + toDate + "','dd/mm/yyyy') GROUP BY m.dccb_name order by m.dccb_name) n");
            }
            labels = new ArrayList<String>();
            while (resultset.next()) {
                labels.add(resultset.getString(1));
            }


            barChartDataObjOut.setLabels(labels);
        } catch (SQLException ex) {
            System.out.println("Error Occurred during processing.");
        } finally {
            try {
                statement.close();
                connection.close();
                resultset.close();

            } catch (SQLException ex) {
               // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during connection close.");
            }

        }


        try {
            connection = LoginDb.DbHandler.getDBConnection();
            proc = connection.prepareCall("{ ?=call Dashboard_Query(?,?,?,?) }");
        } catch (SQLException ex) {
           // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } finally {
            try {
                datasets = new ArrayList<datasets>();


                proc.registerOutParameter(1, OracleTypes.CURSOR);
                proc.setString(2, fromDate);
                proc.setString(3, toDate);
                proc.setString(4, distCode);
                proc.setString(5, reportSelection);

                proc.executeUpdate();

                rs = (ResultSet) proc.getObject(1);
                int k = 0;
                String x = "";
                rs.next();
                for (i = 0; i < labels.size(); i++) {

                    if (i % labels.size() == 0) {
                        datasetsObj1 = new datasets();
                        datasetsObj2 = new datasets();
                        color = randColors.get(k++);
                        x = rs.getString(2);
                        datasetsObj1.setLabel(x);
                        datasetsObj2.setLabel(x);
                        datasetsObj1.setBackgroundColor(color);
                        datasetsObj2.setBackgroundColor(color);
                        data1 = new ArrayList<Integer>();
                        data2 = new ArrayList<Integer>();

                        data1.add(rs.getInt(2));
                        data2.add(rs.getInt(3));
                        rs.next();

                    } else if (i % labels.size() == labels.size() - 1) {

                        data1.add(rs.getInt(2));
                        data2.add(rs.getInt(3));
                        rs.next();

                        datasetsObj1.setData(data1);
                        datasets.add(datasetsObj1);
                        datasetsObj2.setData(data2);
                        datasets.add(datasetsObj2);




                    } else {

                        data1.add(rs.getInt(2));
                        data2.add(rs.getInt(3));
                        rs.next();

                    }


                }
                barChartDataObjOut.setDatasets(datasets);

            } catch (Exception ex) {
                System.out.println("Error Occurred during processing.");
            } finally {

                try {
                    proc.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }                
                try {
                    rs.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(JsonDbHandler.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }

               // return barChartDataObjOut;
            }
            try {
                    connection.close();
                } catch (SQLException ex) {
                   System.out.println("Error Occurred during connection close.");
                }
        }
        return barChartDataObjOut;
    }

    public barChartData selectionGraph(String toDate, String fromDate, String distCode, String reportSelection) {
        barChartData barChartDataObjOut = null;
        barChartDataObjOut = new barChartData();
        if (reportSelection.equalsIgnoreCase("1")) {
            barChartDataObjOut = getGraphData(toDate, fromDate, distCode, reportSelection);
        } else if (reportSelection.equalsIgnoreCase("2")) {
            barChartDataObjOut = getGraphData1(toDate, fromDate, distCode, reportSelection);
        } else if (reportSelection.equalsIgnoreCase("4")) {
            barChartDataObjOut = getGraphData3(toDate, fromDate, distCode, reportSelection);
        } else if (reportSelection.equalsIgnoreCase("5")) {
            barChartDataObjOut = getGraphData4(toDate, fromDate, distCode, reportSelection);
        } else if (reportSelection.equalsIgnoreCase("3")) {
            barChartDataObjOut = getGraphData2(toDate, fromDate, distCode, reportSelection);
        } else if (reportSelection.equals("6")) {
            barChartDataObjOut = getGraphData5(toDate, fromDate, distCode, reportSelection);
        }

        return barChartDataObjOut;
    }
}
