org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for org.openmrs.module.tracnetreporting.impl.TracNetIndicatorServiceImpl.java

Source

/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.tracnetreporting.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.openmrs.Patient;
import org.openmrs.Person;
import org.openmrs.api.context.Context;
import org.openmrs.module.tracnetreporting.GlobalProperties;
import org.openmrs.module.tracnetreporting.service.ConstantValues;
import org.openmrs.module.tracnetreporting.service.TracNetIndicatorService;

/**
 * Implements the interface <code>TracNetIndicatorService</code>: The TracNet
 * Indicators Service deal with Indicators.
 */
public class TracNetIndicatorServiceImpl implements TracNetIndicatorService {

    private Log log = LogFactory.getLog(getClass());

    private SessionFactory sessionFactory;

    /**
     * @param sessionFactory
     *            the sessionFactory to set
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * @return the sessionFactory
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    // ------Getting the Maximum Date------------

    private String maxDateForNextVisit(int patientId) throws ParseException {

        Date maxDate;
        String returnedDate = "";
        String returnValue = "";

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session
                    .createSQLQuery("select  cast(MAX(obs.value_datetime) as DATE) from obs where obs.concept_id = "
                            + ConstantValues.NEXT_SCHEDULED_VISIT + " and obs.person_id = " + patientId
                            + " group by obs.person_id");

            Date record = (Date) query.uniqueResult();

            DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

            if (record != null) {

                maxDate = record;
                returnedDate = sdf.format(maxDate);
            }

            returnValue = returnedDate;
        } catch (Exception e) {
            // TODO: handle exception
        }

        return returnValue;
    }

    @SuppressWarnings({ "static-access", "unused" })
    private List<Patient> listOfPatients(List<Integer> patientIds, String startDate) throws ParseException {

        List<Patient> patients = new ArrayList<Patient>();

        try {
            DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            Date startingDate = sdf.parse(startDate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(startingDate);

            // subtracting 3 months to the given date.
            cal.add(2, -2);

            String realDate = cal.get(cal.YEAR) + "/" + cal.get(cal.MONTH) + "/" + cal.get(cal.DATE);
            startingDate = sdf.parse(realDate);

            for (Integer patientId : patientIds) {

                if (!maxDateForNextVisit(patientId).equals("")) {
                    Date maxDate = sdf.parse(maxDateForNextVisit(patientId));

                    if (maxDate.compareTo(startingDate) < 0) {

                        Patient patient = Context.getPatientService().getPatient(patientId);

                        if (!patient.getPersonVoided()) {

                            patients.add(patient);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return patients;
    }

    /**
     * Returns minimum date for every patientId entered
     * 
     * @throws ParseException
     */
    @SuppressWarnings("unused")
    private boolean returnMinOrderDateForPatient(Integer patientId, String startingDate, String endingDate)
            throws ParseException {

        boolean patientIsStarting = false;

        try {
            Session session = getSessionFactory().getCurrentSession();
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            Date startDate = df.parse(startingDate);
            Date endDate = df.parse(endingDate);
            Date patientMinDate = (Date) session
                    .createSQLQuery("SELECT MIN(start_date) FROM orders WHERE patient_id = " + patientId)
                    .uniqueResult();

            if (patientMinDate != null && patientMinDate.getTime() <= endDate.getTime()
                    && patientMinDate.getTime() >= startDate.getTime())
                patientIsStarting = true;
        } catch (Exception e) {
            // TODO: handle exception
        }

        return patientIsStarting;
    }

    /**
     * Utility method to add days to an existing date
     * 
     * @param date
     *            (may be null to use today's date)
     * @param days
     *            the number of days to add (negative to subtract days)
     * @return the new date
     * @throws ParseException
     */
    public String addDaysToDate(String date, int months) throws ParseException {
        // Initialize with date if it was specified
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        Calendar cal = Calendar.getInstance();
        try {
            if (date != null)
                cal.setTime(df.parse(date));

            cal.add(Calendar.MONTH, months);
        } catch (Exception e) {
            // TODO: handle exception
        }

        return df.format(cal.getTime());
    }

    public String addDaysToDateUsingDays(String date, int days) throws ParseException {
        // Initialize with date if it was specified
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        Calendar cal = Calendar.getInstance();
        try {
            if (date != null)
                cal.setTime(df.parse(date));

            cal.add(Calendar.DAY_OF_MONTH, days);
        } catch (Exception e) {
            // TODO: handle exception
        }

        return df.format(cal.getTime());
    }

    /**
     * Auto generated method comment
     * 
     * @param patients
     * @param startDate
     * @param age
     * @return
     * @throws ParseException
     */

    @SuppressWarnings("unused")
    private List<Patient> patientsNotLostToFollowup(List<Integer> patients, String startDate, String endDate,
            String age) throws ParseException {

        List<Patient> patientsList = new ArrayList<Patient>();
        // try {
        // List<Integer> patientIdsList = new ArrayList<Integer>();
        // Date maxReturnVisitDay = null;
        // DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        // Date newStartDate = df.parse(startDate);
        // Date threeMonthsBeforeStartDate = addDaysToDate(startDate, -92);
        //
        // Session session = getSessionFactory().getCurrentSession();
        // List<Integer> patientIds = session
        // .createSQLQuery(
        // "select distinct pg.patient_id from patient_program pg "
        // + "inner join program pro on pg.program_id = pro.program_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "inner join obs o on pg.patient_id = o.person_id "
        // + "inner join encounter en on pg.patient_id = en.patient_id "
        // + "inner join orders ord on pg.patient_id = ord.patient_id "
        // + "where DATEDIFF('"
        // + endDate
        // + "', pe.birthdate) "
        // + age
        // + " and ord.concept_id in "
        // + ConstantValues.LIST_OF_ARV_DRUGS
        // +
        // " and ord.date_stopped is null and pg.voided = false and pe.voided = false and ord.voided = false and o.voided = false "
        // + " and pa.voided = false and en.voided = false and o.concept_id <> "
        // + ConstantValues.REASON_FOR_EXITING_CARE
        // + " and o.obs_datetime <= '" + endDate
        // + "' and ord.date_activated <= '" + endDate
        // + "' and o.concept_id = "
        // + ConstantValues.NEXT_SCHEDULED_VISIT
        // + " and pg.program_id= "
        // + ConstantValues.HIV_PROGRAM_ID
        // + " and pg.date_completed is null ").list();
        //
        // for (Integer patientId : patientIds) {
        //
        // Date maxEncounterDateTime = (Date) session.createSQLQuery(
        // "select max(encounter_datetime) from encounter where patient_id = "
        // + patientId).uniqueResult();
        //
        // maxReturnVisitDay = (Date) session.createSQLQuery(
        // "select cast(max(value_datetime) as DATE ) "
        // + "from obs where concept_id = "
        // + ConstantValues.NEXT_SCHEDULED_VISIT
        // + " and person_id = " + patientId)
        // .uniqueResult();
        //
        // if (maxReturnVisitDay.getTime() < newStartDate.getTime()) {
        //
        // if ((maxEncounterDateTime.getTime() > threeMonthsBeforeStartDate
        // .getTime() && maxEncounterDateTime.getTime() <= newStartDate
        // .getTime())
        // || (maxReturnVisitDay.getTime() > threeMonthsBeforeStartDate
        // .getTime() && maxReturnVisitDay.getTime() <= newStartDate
        // .getTime())) {
        //
        // patientIdsList.add(patientId);
        //
        // }
        // } else if (maxReturnVisitDay.getTime() > newStartDate.getTime()) {
        //
        // patientIdsList.add(patientId);
        // }
        // }
        //
        // // Retaining all those patients who are not lost to follow-up
        //
        // patients.retainAll(patientIdsList);
        //
        // for (Integer patientId : patients)
        // patientsList.add(Context.getPatientService().getPatient(
        // patientId));
        // } catch (Exception e) {
        // // TODO: handle exception
        // }
        //
        return patientsList;
    }

    /**
     * Auto generated method comment
     * 
     * @param sessionFactory
     * @param startDate
     * @param endDate
     * @return
     */

    @SuppressWarnings("unused")
    private List<Integer> isPatientsOnArvsThisMonth(Session session, String startDate, String endDate) {

        List<Integer> patientIds = new ArrayList<Integer>();

        // try {
        //
        // SQLQuery query = session
        // .createSQLQuery("SELECT DISTINCT pp.patient_id FROM patient_program pp "
        // + "INNER JOIN program pro ON pro.program_id = pp.program_id "
        // + "INNER JOIN patient pat ON pat.patient_id = pp.patient_id "
        // + "INNER JOIN person pe ON pe.person_id = pat.patient_id "
        // +
        // "INNER JOIN orders ord ON ord.patient_id = pat.patient_id WHERE pp.program_id= "
        // + ConstantValues.HIV_PROGRAM_ID
        // +
        // " AND pe.dead = FALSE AND pat.voided = FALSE  AND ord.concept_id IN "
        // + ConstantValues.LIST_OF_ARV_DRUGS
        // + " AND ord.voided = FALSE AND ord.void_reason IS NULL "
        // + "AND (ord.date_activated not between '"
        // + startDate
        // + "' AND '"
        // + endDate
        // + "' OR ord.date_activated > '"
        // + endDate
        // +
        // "') AND ord.date_stopped IS NULL AND ord.discontinued = FALSE");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        //
        // patientIds = query.list();
        //
        // } catch (Exception e) {
        // // TODO: handle exception
        // }
        return patientIds;
    }

    @SuppressWarnings({ "unused" })
    private List<Integer> PatientsOnArvsThisMonth(Session session, String startDate, String endDate, String age) {

        List<Integer> patientIds = new ArrayList<Integer>();
        // try {
        //
        // SQLQuery query = session
        // .createSQLQuery("SELECT DISTINCT pp.patient_id FROM patient_program pp "
        // + "INNER JOIN program pro ON pro.program_id = pp.program_id "
        // + "INNER JOIN patient pat ON pat.patient_id = pp.patient_id "
        // + "INNER JOIN person per ON per.person_id = pat.patient_id "
        // +
        // "INNER JOIN orders ord ON ord.patient_id = pat.patient_id WHERE DATEDIFF('"
        // + endDate
        // + "', per.birthdate) "
        // + age
        // + " and pp.program_id= "
        // + ConstantValues.HIV_PROGRAM_ID
        // +
        // " AND per.dead = FALSE AND pat.voided = FALSE  AND ord.concept_id IN "
        // + ConstantValues.LIST_OF_ARV_DRUGS
        // + " AND ord.voided = FALSE AND ord.void_reason IS NULL "
        // + "AND (ord.date_activated not between '"
        // + startDate
        // + "' AND '"
        // + endDate
        // + "' OR ord.date_activated > '"
        // + endDate
        // +
        // "') AND ord.date_stopped IS NULL AND ord.discontinued = FALSE");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // patientIds = query.list();
        //
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return patientIds;
    }

    @SuppressWarnings("unused")
    private boolean areAllOrdersDiscontinued(Patient patient) {
        boolean allOrdersAreDiscontinued = true;
        // try {
        // List<Order> patientOrders = new ArrayList<Order>();
        //
        // patientOrders = Context.getOrderService().getOrdersByPatient(
        // patient);
        // for (Order order : patientOrders) {
        // if (order.getDiscontinued() == false) {
        // allOrdersAreDiscontinued = false;
        // break;
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return allOrdersAreDiscontinued;
    }

    // --------A. PRE-ART Data Elements-----------

    /**
     * Total number of new pediatric patients (age <18 months) enrolled in HIV
     * care
     * 
     * @throws ParseException
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderEighteenMonthsInHivCare(java.util.Date,
     *      java.util.Date)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsUnderEighteenMonthsInHivCare(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and pg.voided = 0 and pe.voided = 0 "
                    + " and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            indicator++;

                        }
                    }
                }
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Total number of new pediatric patients (age <5 years) enrolled in HIV
     * care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderFiveInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsUnderFiveInHivCare(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and pg.voided = 0 and pe.voided = 0 "
                    + " and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            indicator++;

                        }
                    }
                }
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of new female pediatric patients (age <15 years) enrolled in
     * HIV care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleUnderFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleUnderFifteenInHivCare(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 "
                    + " and pe.gender = 'F' and pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            indicator++;

                        }
                    }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of new male pediatric patients (age <15 years) enrolled in
     * HIV care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleUnderFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleUnderFifteenInHivCare(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 "
                    + " and pe.gender = 'M' and pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            indicator++;

                        }
                    }
                }
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of new female adult patients (age 15+) enrolled in HIV care
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleMoreThanFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleMoreThanFifteenInHivCare(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        // Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pg.voided = 0 and pe.voided = 0 "
                    + " and pa.voided = 0 and pe.gender = 'F' and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDateEnrolled = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDateEnrolled.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            indicator++;

                        }

                    }
                }

            }

        }

        catch (Exception e) {

            e.printStackTrace();

        }
        return indicator;
    }

    /**
     * Total number of new male adult patients (age 15+) enrolled in HIV care
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleMoreThanFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleMoreThanFifteenInHivCare(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        // Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Session session = getSessionFactory().getCurrentSession();

        /* try { */

        SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                + "inner join person pe on pg.patient_id = pe.person_id "
                + "inner join patient pa on pg.patient_id = pa.patient_id "
                + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 "
                + " and pg.voided = 0 and pe.voided = 0 "
                + " and pa.voided = 0 and pe.gender = 'M' and pg.date_enrolled >= '" + startDate
                + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

        List<Integer> patientIds1 = query1.list();

        for (Integer patientId : patientIds1) {

            SQLQuery queryDateEnrolled = session.createSQLQuery(
                    "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                            + patientId);
            List<Date> dateEnrolled = queryDateEnrolled.list();

            if (dateEnrolled.get(0) != null) {

                if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                        && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                {

                    SQLQuery queryTransferredIn = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                    + " and o.voided = 0 and o.person_id= " + patientId);

                    List<Integer> patientIds4 = queryTransferredIn.list();

                    if (patientIds4.size() == 0) {

                        indicator++;

                    }
                }
            }
        }

        /*
         * catch (Exception e) {
         * 
         * e.printStackTrace();
         */
        // }
        return indicator;
    }

    /**
     * Total number of pediatric patients (age <18 months) ever enrolled in HIV
     * care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedUnderEighteenMonthsEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    public int pedUnderEighteenMonthsEverInHiv(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and d.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided =0 and pa.voided = 0 and ord.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        + "inner join drug d on do.drug_inventory_id = d.drug_id " + "where d.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                        + endDate + "'" + " and pg.voided = 0 and pe.voided =0 and pa.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of pediatric patients (age <5 years) ever enrolled in HIV
     * care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pedsUnderFiveEverInHiv(String startDate, String endDate) {

        int indicator = 0;

        /*
         * try {
         * 
         * Session session = getSessionFactory().getCurrentSession();
         * 
         * SQLQuery query1 = session
         * .createSQLQuery("select distinct pg.patient_id from patient_program pg "
         * + "inner join person pe on pg.patient_id = pe.person_id " +
         * "inner join patient pa on pg.patient_id = pa.patient_id " +
         * "inner join orders ord on pg.patient_id = ord.patient_id " +
         * "inner join drug_order do on ord.order_id = do.order_id " +
         * "inner join drug d on do.drug_inventory_id = d.drug_id " +
         * "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate +
         * "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " +
         * " and d.concept_id IN (" +
         * GlobalProperties.gpGetListOfProphylaxisDrugs() +
         * ") and (cast(ord.date_activated as DATE)) <= '" + endDate +
         * "' and pg.date_enrolled <= '" + endDate +
         * "' and pg.voided =0 and pe.voided =0 and pa.voided = 0 and pg.program_id = "
         * + Integer.parseInt(GlobalProperties .gpGetHIVProgramId()));
         * 
         * List<Integer> patientIds1 = query1.list();
         * 
         * for (Integer patientId : patientIds1) {
         * 
         * SQLQuery query2 = session
         * .createSQLQuery("select distinct pg.patient_id from patient_program pg "
         * + "inner join person pe on pg.patient_id = pe.person_id " +
         * "inner join patient pa on pg.patient_id = pa.patient_id " +
         * "inner join orders ord on pg.patient_id = ord.patient_id " +
         * "inner join drug_order do on ord.order_id = do.order_id " +
         * "inner join drug d on do.drug_inventory_id = d.drug_id " +
         * "where d.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() +
         * ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "'" +
         * " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.patient_id="
         * + patientId);
         * 
         * List<Integer> patientIds2 = query2.list();
         * 
         * if (patientIds2.size() == 0) {
         * 
         * indicator++;
         * 
         * } } }
         * 
         * catch (Exception e) { e.printStackTrace(); }
         */
        return indicator;
    }

    /**
     * Total number of female pediatric patients (age <15 years) ever enrolled
     * in HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femalePedsUnderFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femalePedsUnderFifteenEverInHiv(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and d.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and pe.gender = 'F' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        + "inner join drug d on do.drug_inventory_id = d.drug_id " + "where d.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                        + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of male pediatric patients (age <15 years) ever enrolled in
     * HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#malePedsUnderFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int malePedsUnderFifteenEverInHiv(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and d.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and pe.gender = 'M' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        + "inner join drug d on do.drug_inventory_id = d.drug_id " + "where d.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                        + " and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of female adult patients (age 15 or older) ever enrolled in
     * HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThanFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleMoreThanFifteenEverInHiv(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pe.gender = 'F' and d.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                    + endDate + "'  and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        + "inner join drug d on do.drug_inventory_id = d.drug_id " + "where d.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                        + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if ((patientIds2.size() == 0)) {

                    indicator++;

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Total number of male adult patients (age 15 or older) ever enrolled in
     * HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThanFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleMoreThanFifteenEverInHiv(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and d.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and pe.gender = 'M' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        + "inner join drug d on do.drug_inventory_id = d.drug_id " + "where d.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                        + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of patients on Cotrimoxazole Prophylaxis this month
     * 
     * @throws ParseException
     * @throws ParseException
     * 
     * @throws ParseException
     * @throws NumberFormatException
     * @throws HibernateException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#patientsOnCotrimoProphylaxis(java.util.Date,
     *      java.util.Date)
     */

    @SuppressWarnings("unchecked")
    @Override
    public int patientsOnCotrimoProphylaxis(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        // try {

        SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                + " inner join person pe on pg.patient_id = pe.person_id "
                + " inner join patient pa on pg.patient_id = pa.patient_id "
                + " inner join orders ord on pg.patient_id = ord.patient_id "
                + " where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                + "')) and ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                + endDate
                + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id =  "
                + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

        List<Integer> patientIds1 = query1.list();

        for (Integer patientId : patientIds1) {

            indicator++;

        }

        return indicator;
    }

    /**
     * Number of new patients screened for active TB at enrollment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#patientsActiveTbAtEnrolThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int patientsActiveTbAtEnrolThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    // +
                    // "inner join drug_order do on ord.order_id = do.order_id "
                    // +
                    // "inner join drug d on do.drug_inventory_id = d.drug_id "

                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                /*
                 * SQLQuery queryExited = session .createSQLQuery(
                 * "select distinct o.person_id from obs o where o.concept_id = "
                 * + Integer.parseInt(GlobalProperties
                 * .gpGetExitFromCareConceptId()) +
                 * " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'" +
                 * " and o.voided = 0 and o.person_id= " + patientId);
                 * 
                 * List<Integer> patientIds3 = queryExited.list();
                 * 
                 * if (patientIds3.size() == 0) {
                 */

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId())
                                + " and (cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfTBScreening = queryDate.list();

                if (dateOfTBScreening.get(0) != null)

                {

                    if ((dateOfTBScreening.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfTBScreening.get(0).getTime() <= newEndDate.getTime())) {

                        indicator++;
                    }
                }
            }
            // }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of patients screened TB Positive at enrollment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#patientsTbPositiveAtEnrolThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int patientsTbPositiveAtEnrolThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "where pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId())
                                    + " and value_coded= "
                                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                                    + " and (cast(obs_datetime as DATE)) is not null  and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfTBScreening = queryDate.list();

                    if (dateOfTBScreening.get(0) != null) {

                        if ((dateOfTBScreening.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfTBScreening.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of newly enrolled patients (age <15 years) who started TB
     * treatment this month?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newEnrolledPedsStartTbTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newEnrolledPedsStartTbTreatThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                    + " and ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryMinStartDate = session
                                .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                        + " inner join drug_order do on ord.order_id = do.order_id "
                                        + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                                        + ") "
                                        + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                        if (patientIdsMinStartDate.get(0) != null)

                        {

                            if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                    && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                                SQLQuery queryExited = session.createSQLQuery(
                                        "select distinct o.person_id from obs o where o.concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                                + " and o.voided = 0 and o.person_id= " + patientId);

                                List<Integer> patientIds3 = queryExited.list();

                                if ((patientIds3.size() == 0)) {

                                    indicator++;

                                }
                            }
                        }
                    }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of newly enrolled patients (age 15+ years) who started TB
     * treatment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newEnrolledAdultsStartTbTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newEnrolledAdultsStartTbTreatThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                    + " and ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {
                        SQLQuery queryMinStartDate = session
                                .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                        + " inner join drug_order do on ord.order_id = do.order_id "
                                        + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                                        + ") "
                                        + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                        if (patientIdsMinStartDate.get(0) != null)

                        {

                            if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                    && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                                SQLQuery queryExited = session.createSQLQuery(
                                        "select distinct o.person_id from obs o where o.concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                                + " and o.voided = 0 and o.person_id= " + patientId);

                                List<Integer> patientIds3 = queryExited.list();

                                if ((patientIds3.size() == 0)) {

                                    indicator++;

                                }
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    // --------Exporting Data to CSV and Excel Files---------

    /**
     * Exports data to the CSV File or Text File
     * 
     * @throws IOException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
     */
    @SuppressWarnings("unchecked")
    @Override
    public void exportDataToCsvFile(HttpServletRequest request, HttpServletResponse response,
            Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
            throws IOException {

        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
        outputStream.println();
        outputStream.println("# , Indicator Name , Indicator");
        outputStream.println();
        int count = 0;

        List<String> indicator_msg = null;

        indicator_msg = (ArrayList<String>) request.getSession().getAttribute(request.getParameter("id") + "_msg");

        for (String indicator : indicatorsList.keySet()) {
            count++;
            outputStream.println(indicator.toString().substring(4) + " , " + indicator_msg.get(count - 1) + " , "
                    + indicatorsList.get(indicator).toString());
        }

        outputStream.flush();
        outputStream.close();
    }

    /**
     * Exports data to the Excel File
     * 
     * @throws IOException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToExcelFile(java.util.Map)
     */
    @SuppressWarnings({ "deprecation", "unchecked" })
    public void exportDataToExcelFile(HttpServletRequest request, HttpServletResponse response,
            Map<String, Integer> indicatorsList, String filename, String title, String startDate, String endDate)
            throws IOException {

        HSSFWorkbook workbook = new HSSFWorkbook();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        HSSFSheet sheet = workbook.createSheet(title);
        int count = 0;
        sheet.setDisplayRowColHeadings(true);

        // Setting Style
        HSSFFont font = workbook.createFont();
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setColor(HSSFFont.COLOR_RED);
        cellStyle.setFillForegroundColor((short) 0xA);

        // Title
        HSSFRow row = sheet.createRow((short) 0);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("");
        row.setRowStyle(cellStyle);
        row.createCell((short) 1).setCellValue("" + title + "(Between " + startDate + " and " + endDate + ")");

        // Headers
        row = sheet.createRow((short) 2);
        row.createCell((short) 0).setCellValue("#");
        row.createCell((short) 1).setCellValue("INDICATOR NAME");
        row.createCell((short) 2).setCellValue("INDICATOR");

        Log log = LogFactory.getLog(this.getClass());
        log.info("00000000000000000000000000000000000000000000000000000000000000000");
        // log.info();

        List<String> indicator_msg = null;

        indicator_msg = (ArrayList<String>) request.getSession().getAttribute(request.getParameter("id") + "_msg");

        for (String indicator : indicatorsList.keySet()) {
            count++;
            row = sheet.createRow((short) count + 3);
            row.createCell((short) 0).setCellValue(indicator.toString().substring(4));
            row.createCell((short) 1).setCellValue(indicator_msg.get(count - 1));// .substring(3)
            row.createCell((short) 2).setCellValue(indicatorsList.get(indicator).toString());
            // log.info("========================>>> "+count);
        }
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    // ------------B. ART Data Elements----------------

    /**
     * Total number of pediatric patients (age <18 months) who are currently on
     * ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderEighteenMonthsCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pedsUnderEighteenMonthsCurrentOnArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }

        } catch (Exception e) {

            e.printStackTrace();

        }
        return indicator;
    }

    /**
     * Total number of pediatric patients (age <5 years) who are currently on
     * ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pedsUnderFiveCurrentOnArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Total number of female pediatric patients (age <15 years) who are
     * currently on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femalePedsUnderFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femalePedsUnderFifteenCurrentOnArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                    + endDate + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }

        } catch (Exception e) {
            e.printStackTrace();

        }
        return indicator;
    }

    /**
     * Total number of male pediatric patients (age <15 years) who are currently
     * on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#malePedsUnderFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int malePedsUnderFifteenCurrentOnArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                    + endDate + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }

        } catch (Exception e) {

            e.printStackTrace();

        }
        return indicator;
    }

    /**
     * Total number of pediatric patients who are on First Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsOnFirstLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pedsOnFirstLineReg(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfFirstLineDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfSecondLineDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Total number of pediatric patients who are on Second Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsOnSecondLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pedsOnSecondLineReg(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + "  and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfSecondLineDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.program_id= " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId())
                    + " and pg.date_enrolled <= '" + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Total number of female adult patients (age 15 or older) who are currently
     * on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThanFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleMoreThanFifteenCurrentOnArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Total number of male adult patients (age 15 or older) who are currently
     * on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThanFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleMoreThanFifteenCurrentOnArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Total number of adult patients who are on First Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultOnFirstLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int adultOnFirstLineReg(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfFirstLineDrugs() + ") and (cast(ord.date_activated as DATE)) <= '"
                    + endDate + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfSecondLineDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return indicator;
    }

    /**
     * Total number of adult patients who are on Second Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultOnSecondLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int adultOnSecondLineReg(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        Session session = getSessionFactory().getCurrentSession();

        try

        {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + "  and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfSecondLineDrugs()
                    + ") and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                indicator++;

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of new pediatric patients (<18 months) starting ARV treatment this
     * month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderEighteenMonthStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsUnderEighteenMonthStartArvThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        indicator++;
                    }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new pediatric patients (age <5 years) starting ARV treatment
     * this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderFiveStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsUnderFiveStartArvThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        indicator++;
                    }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of new female pediatric patients (age <15 years) starting ARV
     * treatment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemalePedsUnderFifteenStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemalePedsUnderFifteenStartArvThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        indicator++;
                    }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of new male pediatric patients (age <15 years) starting ARV
     * treatment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMalePedsUnderFifteenStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMalePedsUnderFifteenStartArvThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {
                            indicator++;
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of new pediatric patients who are WHO stage 4 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageFourThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsWhoStageFourThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    for (Date patientIdpatientIdsMinStartDate : patientIdsMinStartDate) {

                        if (patientIdpatientIdsMinStartDate != null)

                            if ((patientIdpatientIdsMinStartDate.getTime() >= newStartDate.getTime())
                                    && patientIdpatientIdsMinStartDate.getTime() <= newEndDate.getTime()) {

                                SQLQuery queryDate = session.createSQLQuery(
                                        "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Date> dateOfWhoStage = queryDate.list();

                                if (dateOfWhoStage.get(0) != null) {

                                    SQLQuery valueCoded = session
                                            .createSQLQuery("select value_coded from obs where concept_id = "
                                                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                    + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                    + dateOfWhoStage.get(0) + " ' "
                                                    + " and value_coded is not null and voided = 0 and person_id = "
                                                    + patientId);

                                    List<Integer> PatientValueCoded = valueCoded.list();

                                    if (PatientValueCoded.get(0) != null) {
                                        if (PatientValueCoded.get(0) == Integer
                                                .parseInt(GlobalProperties.gpGetWhoStageFourPedsConceptId())) {

                                            indicator++;
                                        }
                                    }
                                }
                            }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Number of new pediatric patients who are WHO Stage 3 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageThreeThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsWhoStageThreeThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime)as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null) {

                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null) {
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageThreePedsConceptId())) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of new pediatric patients who are WHO Stage 2 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageTwoThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsWhoStageTwoThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "'  ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null) {

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null) {

                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null) {
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageTwoPedsConceptId())) {

                                        indicator++;
                                    }
                                }
                            }

                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of new pediatric patients who are WHO Stage 1 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageOneThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsWhoStageOneThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "inner join drug d on do.drug_inventory_id = d.drug_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null)

                            {

                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null)

                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageOnePedsConceptId())) {

                                        indicator++;
                                    }
                            }
                        }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of new pediatric patients whose WHO Stage is undefined this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUndefinedWhoStageThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newPedsUndefinedWhoStageThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null)

                            {

                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null)

                                {

                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetUnknownStageConceptId())) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Number of new female adult patients (age 15+) starting ARV treatment this
     * month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleAdultStartiArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleAdultStartiArvThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                {

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        indicator++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of new male adult patients (age 15+) starting ARV treatment this
     * month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleAdultStartiArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleAdultStartiArvThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        {
                            indicator++;
                        }
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of new adult patients who are WHO stage 4 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageFourThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAdultWhoStageFourThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null)

                            {

                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null)

                                {
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageFourAdultConceptId())) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return indicator;

    }

    /**
     * Number of new adult patients who are WHO stage 3 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageThreeThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAdultWhoStageThreeThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null)

                            {
                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null)

                                {
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageThreeAdultConceptId())) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new adult patients who are WHO stage 2 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageTwoThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAdultWhoStageTwoThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.size() != 0) {

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                        {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.size() != 0) {
                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.size() != 0)
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageTwoAdultConceptId())) {

                                        indicator++;
                                    }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new adult patients who are WHO stage 1 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageOneThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAdultWhoStageOneThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null)

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null) {
                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null) {
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetWhoStageOneAdultConceptId())) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Number of new adult patients who are WHO stage undefined this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultUndefinedWhoStageThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAdultUndefinedWhoStageThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0)

                {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.get(0) != null) {

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryDate = session.createSQLQuery(
                                    "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfWhoStage = queryDate.list();

                            if (dateOfWhoStage.get(0) != null)

                            {
                                SQLQuery valueCoded = session
                                        .createSQLQuery("select value_coded from obs where concept_id = "
                                                + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                                + " and (select(cast(obs_datetime as Date))) = " + "'"
                                                + dateOfWhoStage.get(0) + " ' "
                                                + " and value_coded is not null and voided = 0 and person_id = "
                                                + patientId);

                                List<Integer> PatientValueCoded = valueCoded.list();

                                if (PatientValueCoded.get(0) != null)

                                {
                                    if (PatientValueCoded.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetUnknownStageConceptId())) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return indicator;

    }

    /**
     * Number of ARV patients (age <15) who have had their treatment interrupted
     * this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsFifteenInterruptTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvPedsFifteenInterruptTreatThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and ord.date_stopped is not null and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDrugs = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsPerPatient = queryDrugs.list();

                    SQLQuery queryDrugsDiscontinued = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsDiscontinuedPerPatient = queryDrugsDiscontinued.list();

                    if (drugsPerPatient.get(0) == drugsDiscontinuedPerPatient.get(0)) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(discontinued_date as DATE) from orders ord "
                                        + "inner join drug_order do on ord.order_id = do.order_id "
                                        /*
                                         * +
                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                         */
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                                        + ") and (select(cast(discontinued_date as DATE))) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> dateOfDiscontinuedDrugs = queryDate.list();

                        boolean n = true;

                        for (Date d : dateOfDiscontinuedDrugs) {

                            if ((d.getTime() >= newStartDate.getTime()) && (d.getTime() <= newEndDate.getTime())) {
                                ;
                            } else {
                                n = false;
                                break;
                            }

                        }

                        if (n == true) {

                            indicator++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of ARV patients (age 15+) who have had their treatment interrupted
     * this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultFifteenInterruptTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvAdultFifteenInterruptTreatThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and ord.date_stopped is not null and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDrugs = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsPerPatient = queryDrugs.list();

                    SQLQuery queryDrugsDiscontinued = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsDiscontinuedPerPatient = queryDrugsDiscontinued.list();

                    if (drugsPerPatient.get(0) == drugsDiscontinuedPerPatient.get(0)) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(discontinued_date as DATE) from orders ord "
                                        + "inner join drug_order do on ord.order_id = do.order_id "
                                        /*
                                         * +
                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                         */
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                                        + ") and (select(cast(discontinued_date as DATE))) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> dateOfDiscontinuedDrugs = queryDate.list();

                        boolean n = true;

                        for (Date d : dateOfDiscontinuedDrugs) {

                            if ((d.getTime() >= newStartDate.getTime()) && (d.getTime() <= newEndDate.getTime())) {
                                ;
                            } else {
                                n = false;
                                break;
                            }

                        }

                        if (n == true) {

                            indicator++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of ARV patients (age <15) who have died this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsDiedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvPedsDiedThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                    + " and ord.date_stopped is not null and ord.order_reason = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                                + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfDeath = queryDate.list();

                if (dateOfDeath.size() != 0)
                    if ((dateOfDeath.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfDeath.get(0).getTime() <= newEndDate.getTime())) {

                        indicator++;
                    }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of ARV patients (age 15+) who have died this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultDiedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvAdultDiedThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                    + " and ord.date_stopped is not null and ord.order_reason = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                                + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfDeath = queryDate.list();

                if (dateOfDeath.size() != 0)
                    if ((dateOfDeath.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfDeath.get(0).getTime() <= newEndDate.getTime())) {

                        indicator++;
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of ARV patients (age <15) lost to followup (>3 months)
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsLostFollowupMoreThreeMonths(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvPedsLostFollowupMoreThreeMonths(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Session session = getSessionFactory().getCurrentSession();

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate1 = session
                            .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                    + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                    + "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                                    + patientId);

                    List<Date> maxEnocunterDateTime = queryDate1.list();

                    SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + endDate
                            + "' and concept_id = "
                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                            + " and (select(cast(max(value_datetime) as DATE))) is not null and voided = 0 and person_id = "
                            + patientId);

                    List<Date> maxReturnVisitDay = queryDate2.list();

                    if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            indicator++;
                        }
                    }

                    else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            indicator++;
                        }
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of ARV patients (age 15+) lost to followup (>3 months)
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultLostFollowupMoreThreeMonths(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvAdultLostFollowupMoreThreeMonths(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate1 = session
                            .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                    + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                    + "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                                    + patientId);

                    List<Date> maxEnocunterDateTime = queryDate1.list();

                    SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE) "
                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + endDate
                            + "' and concept_id = "
                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                            + " and (select(cast(max(value_datetime) as DATE))) is not null and voided = 0 and person_id = "
                            + patientId);

                    List<Date> maxReturnVisitDay = queryDate2.list();

                    if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            indicator++;
                        }
                    }

                    else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            indicator++;
                        }
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of male patients on treatment 12 months after initiation of ARVs
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleOnTreatTwelveAfterInitArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleOnTreatTwelveAfterInitArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date oneYearBeforeStartDate = df.parse(addDaysToDate(startDate, -12));

        Date oneYearBeforeEndDate = df.parse(addDaysToDate(endDate, -12));

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where pe.gender = 'M' and ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") " + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '"
                    + df.format(oneYearBeforeStartDate) + "' and (cast(ord.date_activated as DATE)) <= '"
                    + df.format(oneYearBeforeEndDate) + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.size() != 0) {

                        Date minStartDate = patientIdsMinStartDate.get(0);

                        if ((minStartDate.getTime() >= oneYearBeforeStartDate.getTime())
                                && (minStartDate.getTime() <= oneYearBeforeEndDate.getTime())) {

                            SQLQuery queryDate1 = session.createSQLQuery(
                                    "select cast(max(encounter_datetime)as DATE) from encounter where "
                                            + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                            + "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                                            + patientId);

                            List<Date> maxEnocunterDateTime = queryDate1.list();

                            SQLQuery queryDate2 = session
                                    .createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                            + endDate + "' and concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                            + " and (select(cast(max(value_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> maxReturnVisitDay = queryDate2.list();

                            if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                                if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                        || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate
                                                .getTime()
                                                && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                                    indicator++;

                                }
                            }

                            else if (((maxReturnVisitDay.get(0)) == null)
                                    && (maxEnocunterDateTime.get(0) != null)) {

                                if ((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime()) {

                                    indicator++;

                                }
                            } else if (((maxReturnVisitDay.get(0) != null))
                                    && (maxReturnVisitDay.get(0).getTime() > newEndDate.getTime()))

                            {
                                indicator++;

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of female patients on treatment 12 months after initiation of ARVs
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleOnTreatTwelveAfterInitArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleOnTreatTwelveAfterInitArv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date oneYearBeforeStartDate = df.parse(addDaysToDate(startDate, -12));

        Date oneYearBeforeEndDate = df.parse(addDaysToDate(endDate, -12));

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where pe.gender = 'F' and ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") " + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '"
                    + df.format(oneYearBeforeStartDate) + "' and (cast(ord.date_activated as DATE)) <= '"
                    + df.format(oneYearBeforeEndDate) + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select(cast(min(ord.date_activated)as Date))) is not null and voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.size() != 0) {

                        Date minStartDate = patientIdsMinStartDate.get(0);

                        if ((minStartDate.getTime() >= oneYearBeforeStartDate.getTime())
                                && (minStartDate.getTime() <= oneYearBeforeEndDate.getTime())) {

                            SQLQuery queryDate1 = session.createSQLQuery(
                                    "select cast(max(encounter_datetime)as DATE) from encounter where "
                                            + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                            + "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                                            + patientId);

                            List<Date> maxEnocunterDateTime = queryDate1.list();

                            SQLQuery queryDate2 = session
                                    .createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                            + endDate
                                            + "' and (select(cast(max(value_datetime) as DATE))) is not null and voided = 0 and concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                            + " and person_id = " + patientId);

                            List<Date> maxReturnVisitDay = queryDate2.list();

                            if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                                if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                        || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate
                                                .getTime()
                                                && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                                    indicator++;

                                }
                            }

                            else if (((maxReturnVisitDay.get(0)) == null)
                                    && (maxEnocunterDateTime.get(0) != null)) {

                                if ((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime()) {

                                    indicator++;

                                }
                            } else if (((maxReturnVisitDay.get(0) != null))
                                    && (maxReturnVisitDay.get(0).getTime() > newEndDate.getTime()))

                            {
                                indicator++;

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * Number of ARV patients (age <15) who have been transferred out this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsTransferredOutThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvPedsTransferredOutThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                                + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfTransferredOut = queryDate.list();

                if (dateOfTransferredOut.size() != 0)
                    if ((dateOfTransferredOut.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfTransferredOut.get(0).getTime() <= newEndDate.getTime())) {

                        indicator++;
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of ARV patients (age 15+) who have been transferred out this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultTransferredOutThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvAdultTransferredOutThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                                + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfTransferredOut = queryDate.list();

                if (dateOfTransferredOut.size() != 0)
                    if ((dateOfTransferredOut.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfTransferredOut.get(0).getTime() <= newEndDate.getTime())) {

                        indicator++;
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

        return indicator;
    }

    /**
     * Number of ARV patients (age <15) who have been transferred in this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsTransferredInThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvPedsTransferredInThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetYesAsAnswerToTransferredInConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                    + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateTransferredIn = queryDate.list();

                    if (dateTransferredIn.size() != 0)
                        if ((dateTransferredIn.get(0).getTime() >= newStartDate.getTime())
                                && (dateTransferredIn.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * Number of ARV patients (age 15+) who have been transferred in this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultTransferreInThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int arvAdultTransferreInThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetYesAsAnswerToTransferredInConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                    + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateTransferredIn = queryDate.list();

                    if (dateTransferredIn.size() != 0)
                        if ((dateTransferredIn.get(0).getTime() >= newStartDate.getTime())
                                && (dateTransferredIn.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    // -------C. STIs, Opportunistic Infections and Others--------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#clientsCounceledForStiThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int clientsCounceledForStiThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#opportInfectTreatedExcludeTbThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int opportInfectTreatedExcludeTbThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryOpportunisticInfectionTB = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                                    + " and o.value_coded = "
                                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionTBConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIdsqueryOpportunisticInfectionTB = queryOpportunisticInfectionTB.list();

                    if (patientIdsqueryOpportunisticInfectionTB.size() == 0) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                                        + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfOpportunisticInfections = queryDate.list();

                        if (dateOfOpportunisticInfections.size() != 0)
                            if ((dateOfOpportunisticInfections.get(0).getTime() >= newStartDate.getTime())
                                    && (dateOfOpportunisticInfections.get(0).getTime() <= newEndDate.getTime())) {

                                indicator++;
                            }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#stiDiagnosedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int stiDiagnosedThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 "
                    + " and pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                    + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionSTIConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(
                                            GlobalProperties.gpGetEndDateOfOpportunisticInfectionSTIConceptId())
                                    + " and (select(cast(obs_datetime as DATE))) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfEndDateOfSTI = queryDate.list();

                    if (dateOfEndDateOfSTI.size() != 0)
                        if ((dateOfEndDateOfSTI.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfEndDateOfSTI.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    // -------D. Nutrition Consultation Data Elements--------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultSevereMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int adultSevereMalnutrTherapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int numberOfPatientsWhoReceivedFollowUpAndAdherenceCounselling(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int numberOfPatientsWhoReceivedFamilyPlanningThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int adultTherapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#lactatingMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int lactatingMalnutrTherapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pedsTherapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFifteenSevMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pedsUnderFifteenSevMalnutrTherapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveSevereMalnutrTheurapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pedsUnderFiveSevereMalnutrTheurapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveSevereMalnutrThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pedsUnderFiveSevereMalnutrThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub

        int indicator = 0;

        // SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        //
        // Date newEndDate = df.parse(endDate);
        //
        // Date newStartDate = df.parse(startDate);
        //
        // Session session = getSessionFactory().getCurrentSession();
        //
        // int weight;
        //
        // int height;
        //
        // int resultWeightHeight;
        //
        // int resultWeightAge;
        //
        // int age;
        //
        // SQLQuery query1 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
        // + endDate
        // + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 5 "
        // + " and pg.program_id= "
        // + Integer
        // .parseInt(GlobalProperties.gpGetHIVProgramId())
        // + " and pg.date_enrolled <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.date_completed is null ");
        //
        // List<Integer> patientIds1 = query1.list();
        //
        // for (Integer patientId : patientIds1) {
        //
        // weight = 0;
        //
        // height = 0;
        //
        // resultWeightHeight = 0;
        //
        // resultWeightAge = 0;
        //
        // age = 0;
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and (cast(o.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and o.voided = 0 and o.person_id="
        // + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0)
        //
        // {
        //
        // SQLQuery queryDateWeight = session
        // .createSQLQuery("select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetWeightConceptId())
        // +
        // " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Date> dateOfWeight = queryDateWeight.list();
        //
        // if (dateOfWeight.size() != 0) {
        // SQLQuery valueNumericOfWeight = session
        // .createSQLQuery("select value_numeric from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetWeightConceptId())
        // + " and (select(cast(obs_datetime as Date))) = "
        // + "'"
        // + dateOfWeight.get(0)
        // + " ' "
        // + " and value_numeric is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Integer> PatientValueNumericOfWeight = valueNumericOfWeight
        // .list();
        //
        // if (PatientValueNumericOfWeight.size() != 0) {
        //
        // weight = PatientValueNumericOfWeight.get(0);
        //
        // }
        //
        // }
        //
        // SQLQuery queryDateHeight = session
        // .createSQLQuery("select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetHeightConceptId())
        // +
        // " and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Date> dateOfHeight = queryDateHeight.list();
        //
        // if (dateOfHeight.size() != 0) {
        // SQLQuery valueNumericOfHeight = session
        // .createSQLQuery("select value_numeric from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetHeightConceptId())
        // + " and (select(cast(obs_datetime as Date))) = "
        // + "'"
        // + dateOfHeight.get(0)
        // + " ' "
        // + " and value_numeric is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Integer> PatientValueNumericOfHeight = valueNumericOfHeight
        // .list();
        //
        // if (PatientValueNumericOfHeight.size() != 0) {
        //
        // height = PatientValueNumericOfHeight.get(0);
        // }
        // }
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded IN ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        //
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // +
        // "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate.list();
        //
        // if (HivTestResultDate.size() != 0)
        //
        // {
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // +
        // "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
        // + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == Integer
        // .parseInt(GlobalProperties
        // .gpGetPositiveAsResultToHIVTestConceptId())) {
        //
        // SQLQuery queryAge = session
        // .createSQLQuery("select DATE_FORMAT(FROM_DAYS(TO_DAYS('"
        // + endDate
        // + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 5 "
        // + " from person pe where pe.voided = 0 and pe.person_id="
        // + patientId);
        //
        // List<Integer> patientIdsAge = queryAge.list();
        //
        // if (patientIdsAge.size() != 0) {
        //
        // age = patientIdsAge.get(0);
        // }
        //
        // resultWeightHeight = weight / height;
        //
        // resultWeightAge = weight / age;
        //
        // if ((resultWeightHeight < -3)
        // || (resultWeightAge < -3)) {
        //
        // indicator++;
        // }
        // }
        // }
        // }
        // }
        // }
        // }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveWithSevMalnutrThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pedsUnderFiveWithSevMalnutrThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub

        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pregnantMalnutrTherapThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    // --------A. Antenatal Data Elements-----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#discordantCouples1(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int discordantCouples1(String startDate, String endDate) {

        int indicator = 0;

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded IN ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {

                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded IN ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultDatePartner = session.createSQLQuery(
                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                            + Integer.parseInt(
                                                    GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                            + " and o.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                            + patientId);
                            List<Date> HivTestResultDatePartner = queryHIVResultDatePartner.list();

                            if (HivTestResultDatePartner.size() != 0) {

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);

                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    SQLQuery queryHIVResultConceptPartner = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and o.value_coded IN ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDatePartner.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConceptPartner = queryHIVResultConceptPartner.list();

                                    if (HivTestResultConceptPartner.size() != 0) {

                                        if (((HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId()))
                                                && (HivTestResultConceptPartner.get(0) == Integer
                                                        .parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())))
                                                || ((HivTestResultConcept.get(0) == Integer.parseInt(
                                                        GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()))
                                                        && (HivTestResultConceptPartner.get(0) == Integer
                                                                .parseInt(GlobalProperties
                                                                        .gpGetNegativeAsResultToHIVTestConceptId())))) {

                                            indicator++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#hivNegPregnantPartnersTestedHivPos(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int hivNegPregnantPartnersTestedHivPos(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded IN ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {

                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded IN ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultDatePartner = session.createSQLQuery(
                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                            + Integer.parseInt(
                                                    GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                            + " and o.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                            + patientId);
                            List<Date> HivTestResultDatePartner = queryHIVResultDatePartner.list();

                            if (HivTestResultDatePartner.size() != 0) {

                                if ((HivTestResultDatePartner.get(0).getTime() >= newStartDate.getTime())
                                        && (HivTestResultDatePartner.get(0).getTime() <= newEndDate.getTime())) {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded IN ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);

                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        SQLQuery queryHIVResultConceptPartner = session.createSQLQuery(
                                                "select o.value_coded from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded IN ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                        + HivTestResultDatePartner.get(0)
                                                        + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                        + patientId);
                                        List<Integer> HivTestResultConceptPartner = queryHIVResultConceptPartner
                                                .list();

                                        if (HivTestResultConceptPartner.size() != 0) {

                                            if ((HivTestResultConcept.get(0) == Integer.parseInt(
                                                    GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId()))
                                                    && (HivTestResultConceptPartner.get(0) == Integer
                                                            .parseInt(GlobalProperties
                                                                    .gpGetPositiveAsResultToHIVTestConceptId()))) {

                                                indicator++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#negativeWomenReturnRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int negativeWomenReturnRes(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pg.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate + "' ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVResultReceivedDate = session.createSQLQuery(
                            "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                                    + " and (select(cast(min(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                    + patientId);
                    List<Date> HivTestResultReceivedDate = queryHIVResultReceivedDate.list();

                    if (HivTestResultReceivedDate.size() != 0) {

                        if ((HivTestResultReceivedDate.get(0).getTime() >= newStartDate.getTime())
                                && (HivTestResultReceivedDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session.createSQLQuery("select distinct pe.person_id from person pe "
                                    + "inner join obs ob on pe.person_id = ob.person_id " + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and ob.voided = 0 and pe.person_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {
                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select(cast(min(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(min(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                            indicator++;
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#partnersTestedHivPos(java.lang.String,
     *      java.lang.String)
     */
    // @SuppressWarnings("unchecked")
    @Override
    public int partnersTestedHivPos(String startDate, String endDate) {

        int indicator = 0;

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "inner join encounter enc on pg.patient_id = enc.patient_id "
        // + "where pe.gender = 'f' and ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) >= '"
        // + startDate
        // + "' AND (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetPMTCTProgramId())
        // + " and pg.date_completed is null ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded IN ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded IN ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate.list();
        //
        // if (HivTestResultDate.size() != 0)
        //
        // {
        //
        // SQLQuery queryHIVResultDatePartner = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and o.value_coded IN ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDatePartner = queryHIVResultDatePartner
        // .list();
        //
        // if (HivTestResultDatePartner.size() != 0) {
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded IN ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        // if (HivTestResultConcept.size() != 0) {
        //
        // SQLQuery queryHIVResultConceptPartner = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDatePartner
        // .get(0)
        // + "' and o.person_id= "
        // + patientId);
        // List<Integer> HivTestResultConceptPartner =
        // queryHIVResultConceptPartner
        // .list();
        //
        // if (HivTestResultConceptPartner.size() != 0) {
        //
        // if ((HivTestResultConcept.get(0) == Integer
        // .parseInt(GlobalProperties
        // .gpGetPositiveAsResultToHIVTestConceptId()))
        // && (HivTestResultConceptPartner
        // .get(0) == Integer
        // .parseInt(GlobalProperties
        // .gpGetPositiveAsResultToHIVTestConceptId()))) {
        //
        // indicator++;
        // }
        // }
        // }
        // }
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPos(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pregnantHivPos(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0)

                        {

                            if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                    && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);
                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    if (HivTestResultConcept.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                        indicator++;
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosAztProphyAt28Weeks(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pregnantHivPosAztProphyAt28Weeks(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosEligibleArvs1(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pregnantHivPosEligibleArvs1(String startDate, String endDate) {

        int indicator = 0;

        double val = 0;

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                    + " and pe.gender = 'f' and (cast(o.obs_datetime as DATE)) <= '" + endDate
                    + "' and pg.program_id= " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and o.voided = 0 ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query2Date = session
                            .createSQLQuery("select cast(max(obs_datetime) as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                                    + " and (select cast(max(obs_datetime) as DATE)) <= '" + endDate
                                    + "' and (select(cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> maxObsDateTimeCD4Count = query2Date.list();

                    if (maxObsDateTimeCD4Count.size() != 0) {

                        SQLQuery query3 = session.createSQLQuery("select value_numeric from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                                + " and obs_datetime = '" + maxObsDateTimeCD4Count.get(0)
                                + "' and value_numeric is not null and voided = 0 and person_id = " + patientId);

                        List<Double> maxValueNumericCD4Count = query3.list();

                        // Double val = (maxValueNumericCD4Count.get(0) > 0) ?
                        // maxValueNumericCD4Count
                        // .get(0)
                        // : 400;

                        // val = maxValueNumericCD4Count.get(0);

                        if (maxValueNumericCD4Count.size() != 0)

                        {

                            if (maxValueNumericCD4Count.get(0) < 350.0) {

                                SQLQuery query4 = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "inner join obs o on pe.person_id = o.person_id "
                                                + "inner join orders ord on pg.patient_id = ord.patient_id "
                                                + "inner join drug_order do on ord.order_id = do.order_id "
                                                /*
                                                 * +
                                                 * "inner join drug d on do.drug_inventory_id = d.drug_id "
                                                 */
                                                + "where ord.concept_id IN ("
                                                + GlobalProperties.gpGetListOfARVsDrugs()
                                                + ") and (cast(ord.date_activated as DATE)) <= '" + endDate
                                                + "' and pg.program_id= "
                                                + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and o.voided = 0 and pg.patient_id =  "
                                                + patientId);

                                List<Integer> patientIds4 = query4.list();

                                if (patientIds4.size() == 0) {

                                    indicator++;

                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosEligibleArvs2(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pregnantHivPosEligibleArvs2(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        double val = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0)

                        {

                            if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                    && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);
                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    if (HivTestResultConcept.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                        SQLQuery queryMinStartDate = session.createSQLQuery(
                                                "select (cast(min(ord.date_activated)as Date)) from orders ord "
                                                        + " inner join drug_order do on ord.order_id = do.order_id "
                                                        /*
                                                         * +
                                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                                         */
                                                        + " where ord.concept_id IN ("
                                                        + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                                        + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                                        + patientId);

                                        List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                                        if (patientIdsMinStartDate.size() != 0) {

                                            if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                                    && patientIdsMinStartDate.get(0).getTime() <= newEndDate
                                                            .getTime()) {

                                                indicator++;
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosTripleTheraProphy(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pregnantHivPosTripleTheraProphy(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantPartnersTestedForHiv(java.lang.String,
     *      java.lang.String)
     */
    // @SuppressWarnings("unchecked")
    @Override
    public int pregnantPartnersTestedForHiv(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        // SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        //
        // Date newEndDate = df.parse(endDate);
        //
        // Date newStartDate = df.parse(startDate);
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "inner join encounter enc on pg.patient_id = enc.patient_id "
        // + "where pe.gender = 'f' and ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) >= '"
        // + startDate
        // + "' AND (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
        // + " and pg.program_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetPMTCTProgramId())
        // + " and pg.date_completed is null ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery queryPartnerHIVTest = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and o.person_id= " + patientId);
        // List<Date> partnerHIVTestDate = queryPartnerHIVTest.list();
        //
        // if (partnerHIVTestDate.size() != 0) {
        //
        // if ((partnerHIVTestDate.get(0).getTime() >= newStartDate
        // .getTime())
        // && (partnerHIVTestDate.get(0).getTime() <= newEndDate
        // .getTime())) {
        //
        // indicator++;
        // }
        // }
        // }
        // }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantTestedPosForRpr(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pregnantTestedPosForRpr(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate + "' ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryCD4CountTest = session.createSQLQuery(
                            "select cast(max(o.obs_datetime) as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                                    + " and o.value_coded IN ("
                                    + GlobalProperties.gpGetListOfAnswersToRapidPlasminReagent()
                                    + ") and (select(cast(max(o.obs_datetime) as DATE))) is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Date> rprTestDate = queryCD4CountTest.list();

                    if (rprTestDate.size() != 0) {

                        if ((rprTestDate.get(0).getTime() >= newStartDate.getTime())
                                && (rprTestDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery queryHIVResult = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                                            + " and o.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToRapidPlasminReagent()
                                            + ") and o.obs_datetime = '" + rprTestDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id="
                                            + patientId);

                            List<Integer> rprTestResult = queryHIVResult.list();

                            if (rprTestResult.size() != 0) {

                                if (rprTestResult.get(0) == Integer.parseInt(GlobalProperties
                                        .gpGetreactiveAsfAnswerToRapidPlasminReagentConceptIdConceptId())) {

                                    indicator++;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosReturnRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosReturnRes(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate + "' and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pg.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVResultReceivedDate = session.createSQLQuery(
                            "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                                    + " and (select(cast(min(o.obs_datetime)as DATE))) and o.voided = 0 and o.person_id="
                                    + patientId);
                    List<Date> HivTestResultReceivedDate = queryHIVResultReceivedDate.list();

                    if (HivTestResultReceivedDate.size() != 0) {

                        if ((HivTestResultReceivedDate.get(0).getTime() >= newStartDate.getTime())
                                && (HivTestResultReceivedDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session.createSQLQuery("select distinct pe.person_id from person pe "
                                    + "inner join obs ob on pe.person_id = ob.person_id " + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and ob.voided = 0 and pe.person_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {
                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select(cast(min(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(min(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            indicator++;
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosTestedCd4(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosTestedCd4(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
                    + " and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryCD4CountTest = session.createSQLQuery(
                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                                    + " and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Date> cd4CountTestDate = queryCD4CountTest.list();

                    if (cd4CountTestDate.size() != 0) {

                        if ((cd4CountTestDate.get(0).getTime() >= newStartDate.getTime())
                                && (cd4CountTestDate.get(0).getTime() <= newEndDate.getTime())) {
                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            indicator++;
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenKnownHivPosFirstAntenatal(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenKnownHivPosFirstAntenatal(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                    + " AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and pe.gender ='f' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate + "' ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinCPNEncounter = session.createSQLQuery(
                            "select cast(min(encounter_datetime)as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                                    + " and (select(cast(min(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id ="
                                    + patientId);

                    List<Date> minCPNEncounter = queryMinCPNEncounter.list();

                    if (minCPNEncounter.size() != 0) {

                        if ((minCPNEncounter.get(0).getTime() >= newStartDate.getTime())
                                && (minCPNEncounter.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {
                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);
                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    if (HivTestResultConcept.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                        indicator++;
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenTestedForRpr(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenTestedForRpr(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate + "' ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryRPRTest = session.createSQLQuery(
                            "select cast(max(o.obs_datetime) as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                                    + " and (select(cast(max(o.obs_datetime) as DATE))) is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Date> rprTestDate = queryRPRTest.list();

                    if (rprTestDate.size() != 0) {

                        if ((rprTestDate.get(0).getTime() >= newStartDate.getTime())
                                && (rprTestDate.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivFirstAntenatal(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenUnknownHivFirstAntenatal(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient pa on pe.person_id = pa.patient_id "
                    + "inner join encounter enc on pe.person_id = enc.patient_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id "
                    + "where enc.encounter_type= " + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                    + " AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and pe.gender ='f' and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 " + " and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate + "' ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinCPNEncounter = session.createSQLQuery(
                            "select cast(min(encounter_datetime)as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                                    + " and (select(cast(min(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id ="
                                    + patientId);

                    List<Date> minCPNEncounter = queryMinCPNEncounter.list();

                    if (minCPNEncounter.size() != 0) {

                        if ((minCPNEncounter.get(0).getTime() >= newStartDate.getTime())
                                && (minCPNEncounter.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session.createSQLQuery("select distinct pe.person_id from person pe "
                                    + "inner join obs ob on pe.person_id = ob.person_id "
                                    + "inner join patient pa on pe.person_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and pe.voided = 0 and ob.voided = 0 and pa.voided = 0 and pe.person_id = "
                                    + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() == 0) {

                                indicator++;
                            }

                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenUnknownHivTested(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id " + "where ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                    + " AND (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and pe.gender ='f' and ob.voided = 0 and pe.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate + "' ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVResultDate = session.createSQLQuery(
                            "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (select(cast(min(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                    + patientId);

                    List<Date> HivTestResultDate = queryHIVResultDate.list();

                    if (HivTestResultDate.size() != 0) {

                        if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    // ----------B. Maternity Data Elements-----------

    @SuppressWarnings("unchecked")
    /*
     * @throws ParseException
     * 
     * @seeorg.openmrs.module.tracnetreporting.service.TracNetIndicatorService#
     * expectedDeliveriesAmongHivPosWomen(java.lang.String, java.lang.String)
     */
    @Override
    public int expectedDeliveriesAmongHivPosWomen(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                    + " and (cast(ob.value_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.value_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
                    + " and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMaternity = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                                    + "where enc.encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and pg.voided = 0 and enc.voided = 0 and pg.patient_id = " + patientId);

                    // Getting the size of the returned LIST which equals to the
                    // COUNTS
                    // needed
                    List<Integer> patientIds3 = queryMaternity.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                                "select cast(max(o.value_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(
                                                GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                                        + " and (select(cast(max(o.value_datetime)as DATE))) is not null and o.voided = 0 and o.person_id= "
                                        + patientId);
                        List<Date> estimateDateOfDelivery = queryEstimatedDateOfDelivery.list();

                        if (estimateDateOfDelivery.size() != 0) {

                            if ((estimateDateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                    && (estimateDateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                                SQLQuery query3 = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "where ob.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                + " and pg.patient_id = " + patientId);

                                List<Integer> patientIds4 = query3.list();

                                if (patientIds4.size() != 0) {

                                    SQLQuery queryHIVResultDate = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDate = queryHIVResultDate.list();

                                    if (HivTestResultDate.size() != 0)

                                    {

                                        SQLQuery queryHIVResultConcept = session.createSQLQuery(
                                                "select o.value_coded from obs o where o.concept_id = "
                                                        + Integer.parseInt(
                                                                GlobalProperties.gpGetResultForHIVTestConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                        + HivTestResultDate.get(0)
                                                        + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                        + patientId);
                                        List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                        if (HivTestResultConcept.size() != 0) {

                                            if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                    GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                                indicator++;
                                            }
                                        }

                                    }

                                }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#expectedDeliveriesFacilityThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int expectedDeliveriesFacilityThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                    + " and (cast(ob.value_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.value_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
                    + " and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMaternity = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                                    + "where enc.encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and pg.voided = 0 and enc.voided = 0 and pg.patient_id = " + patientId);

                    // Getting the size of the returned LIST which equals to the
                    // COUNTS
                    // needed
                    List<Integer> patientIds3 = queryMaternity.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                                "select cast(max(o.value_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(
                                                GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                                        + " and (select(cast(max(o.value_datetime)as DATE))) is not null and o.voided = 0 and o.person_id= "
                                        + patientId);
                        List<Date> estimateDateOfDelivery = queryEstimatedDateOfDelivery.list();

                        if (estimateDateOfDelivery.size() != 0) {

                            if ((estimateDateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                    && (estimateDateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                                indicator++;
                            }
                        }

                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#occuringDeliveriesFacilityThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int occuringDeliveriesFacilityThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select(cast(encounter_datetime as DATE))) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {
                            indicator++;
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantReceivedCompleteCourseThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int pregnantReceivedCompleteCourseThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#reportedHivPosGivingBirthAtHome(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int reportedHivPosGivingBirthAtHome(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosAzt3tcNvpDuringLabor(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int womenHivPosAzt3tcNvpDuringLabor(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosGivingBirthAtFacility(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosGivingBirthAtFacility(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select(cast(encounter_datetime as DATE))) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds4 = query3.list();

                            if (patientIds4.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {
                                            indicator++;
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenReceivingAzt3tcAfterDelivery(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int womenReceivingAzt3tcAfterDelivery(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivStatusTestedDuringLabor1(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenUnknownHivStatusTestedDuringLabor1(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient pa on pe.person_id = pa.patient_id " + "where ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and ob.value_numeric = 1 ");

            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVTestInDeliveryRoom = session.createSQLQuery(
                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                                    + " and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.value_numeric = 1 and o.person_id= "
                                    + patientId);
                    List<Date> testInDeliveryRoomDate = queryHIVTestInDeliveryRoom.list();

                    if (testInDeliveryRoomDate.size() != 0) {

                        if ((testInDeliveryRoomDate.get(0).getTime() >= newStartDate.getTime())
                                && (testInDeliveryRoomDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery queryHIVTest = session
                                    .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.obs_datetime < '" + testInDeliveryRoomDate.get(0)
                                            + "' and o.voided = 0 and o.person_id=" + patientId);

                            List<Integer> patientIds3 = queryHIVTest.list();

                            if (patientIds3.size() == 0) {

                                indicator++;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivStatusTestedPosDuringLabor2(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenUnknownHivStatusTestedPosDuringLabor2(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient pa on pe.person_id = pa.patient_id " + "where ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and ob.value_numeric = 1 ");

            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVTestInDeliveryRoom = session.createSQLQuery(
                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                                    + " and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.value_numeric = 1 and o.person_id= "
                                    + patientId);
                    List<Date> testInDeliveryRoomDate = queryHIVTestInDeliveryRoom.list();

                    if (testInDeliveryRoomDate.size() != 0) {

                        if ((testInDeliveryRoomDate.get(0).getTime() >= newStartDate.getTime())
                                && (testInDeliveryRoomDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery queryHIVTest = session
                                    .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.obs_datetime < '" + testInDeliveryRoomDate.get(0)
                                            + "' and o.voided = 0 and o.person_id=" + patientId);

                            List<Integer> patientIds3 = queryHIVTest.list();

                            if (patientIds3.size() == 0) {

                                SQLQuery query4 = session
                                        .createSQLQuery("select distinct pe.person_id from person pe "
                                                + "inner join obs ob on pe.person_id = ob.person_id "
                                                + "where ob.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and pe.voided = 0 and ob.voided = 0 and pe.person_id = "
                                                + patientId);

                                List<Integer> patientIds4 = query4.list();

                                if (patientIds4.size() != 0) {

                                    SQLQuery queryHIVResultDate = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDate = queryHIVResultDate.list();

                                    if (HivTestResultDate.size() != 0)

                                    {

                                        if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                                && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                                            SQLQuery queryHIVResultConcept = session.createSQLQuery(
                                                    "select o.value_coded from obs o where o.concept_id = "
                                                            + Integer.parseInt(GlobalProperties
                                                                    .gpGetResultForHIVTestConceptId())
                                                            + " and o.value_coded in ("
                                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                            + HivTestResultDate.get(0)
                                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                            + patientId);
                                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                            if (HivTestResultConcept.size() != 0) {

                                                if (HivTestResultConcept.get(0) == Integer.parseInt(GlobalProperties
                                                        .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    indicator++;
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    // ---------C. HIV Exposed Infant Follow-up-----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersAged6WeeksThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int infantHivPosMothersAged6WeeksThisMonth(String startDate, String endDate) {
        int indicator = 0;

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct rel.person_a from relationship rel "
        // + "inner join person pe on rel.person_a = pe.person_id "
        // + "where pe.gender = 'f' "
        // + " and rel.voided = 0 and pe.voided = 0 ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate
        // .list();
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == Integer
        // .parseInt(GlobalProperties
        // .gpGetPositiveAsResultToHIVTestConceptId())) {
        //
        // SQLQuery infantHIVPositiveInPMTCT = session
        // .createSQLQuery("select distinct rel.person_b from relationship rel "
        // + "inner join person pe on rel.person_b = pe.person_id "
        // + "inner join encounter en on rel.person_b = en.patient_id "
        // + "inner join patient_program pg on rel.person_b = pg.patient_id "
        // + "where rel.person_a = "
        // + patientId
        // + " and pe.birthdate >= '"
        // + startDate
        // + "' and pe.birthdate <= '"
        // + startDate
        // + "' and SELECT DATEDIFF(('"
        // + endDate
        // + "'),pe.birthdate)/30 < 2 ");
        // List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
        // .list();
        //
        // if (infantHIVPositive.size() != 0) {
        //
        // indicator++;
        // }
        // }
        //
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersAged9MonthsThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int infantHivPosMothersAged9MonthsThisMonth(String startDate, String endDate) {
        int indicator = 0;

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct rel.person_a from relationship rel "
        // + "inner join person pe on rel.person_a = pe.person_id "
        // + "where pe.gender = 'f' "
        // + " and rel.voided = 0 and pe.voided = 0 ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate
        // .list();
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTestAsIntegers()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == Integer
        // .parseInt(GlobalProperties
        // .gpGetPositiveAsResultToHIVTestConceptId())) {
        //
        // SQLQuery infantHIVPositiveInPMTCT = session
        // .createSQLQuery("select distinct rel.person_b from relationship rel "
        // + "inner join person pe on rel.person_b = pe.person_id "
        // + "inner join encounter en on rel.person_b = en.patient_id "
        // + "inner join patient_program pg on rel.person_b = pg.patient_id "
        // + "where rel.person_a = "
        // + patientId
        // + " and pe.birthdate >= '"
        // + startDate
        // + "' and pe.birthdate <= '"
        // + startDate
        // + "' and SELECT DATEDIFF(('"
        // + endDate
        // + "'),pe.birthdate)/30 = 9 ");
        // List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
        // .list();
        //
        // if (infantHIVPositive.size() != 0) {
        //
        // indicator++;
        // }
        // }
        //
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersAgedAt18MonthsThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int infantHivPosMothersAgedAt18MonthsThisMonth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersCotrimoAt6Weeks(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int infantHivPosMothersCotrimoAt6Weeks(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersEnrolledPmtct(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersEnrolledPmtct(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = queryExited.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + "inner join person pe on rel.person_b = pe.person_id "
                                                    + "inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + "where rel.person_a = " + patientId + " and pg.program_id = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())

                                                    + " and pg.voided = 0  and rel.voided = 0 and (cast(pg.date_enrolled as DATE)) >= '"
                                                    + startDate + "' and (cast(pg.date_enrolled as DATE)) <= '"
                                                    + endDate + "' ");
                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() != 0) {

                                                SQLQuery queryExposedInfantInPMTCT = session.createSQLQuery(
                                                        "select (cast(pg.date_enrolled as DATE)) from patient_program pg"
                                                                + " where pg.patient_id = " + patientIdsInfant
                                                                + " and (select(cast(pg.date_enrolled as DATE))) is not null and pg.voided = 0 and pg.program_id = "
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId()));

                                                List<Date> exposedInfantInPMTCT = queryExposedInfantInPMTCT.list();

                                                if ((exposedInfantInPMTCT.get(0).getTime() >= newStartDate
                                                        .getTime())
                                                        && (exposedInfantInPMTCT.get(0).getTime() <= newEndDate
                                                                .getTime())) {

                                                    indicator++;
                                                }
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersLostFollowup(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersLostFollowup(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id = "
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and pg.voided = 0 and rel.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id= "
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryDate1 = session.createSQLQuery(
                                                        "select cast(max(encounter_datetime)as DATE) from encounter where "
                                                                + "(select(cast(max(encounter_datetime)as Date))) <= '"
                                                                + endDate
                                                                + "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                                                                + patientIdsInfant);

                                                List<Date> maxEnocunterDateTime = queryDate1.list();

                                                SQLQuery queryDate2 = session
                                                        .createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                                                + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                                                + endDate + "' and concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetReturnVisitDateConceptId())
                                                                + " and (select(cast(max(value_datetime) as DATE ))) is not null and voided = 0 and person_id = "
                                                                + patientIdsInfant);

                                                List<Date> maxReturnVisitDay = queryDate2.list();

                                                if (((maxReturnVisitDay.get(0)) != null)
                                                        && (maxEnocunterDateTime.size() != 0)) {

                                                    if (((maxEnocunterDateTime.get(0)
                                                            .getTime()) >= threeMonthsBeforeEndDate.getTime()
                                                            && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                                                                    .getTime())
                                                            || ((maxReturnVisitDay.get(0)
                                                                    .getTime()) >= threeMonthsBeforeEndDate
                                                                            .getTime()
                                                                    && (maxReturnVisitDay.get(0)
                                                                            .getTime()) <= newEndDate.getTime())) {

                                                        patientsNotLostToFollowUp.add(patientId);

                                                    }

                                                    else {

                                                        indicator++;
                                                    }
                                                }

                                                else if (((maxReturnVisitDay.get(0)) == null)
                                                        && (maxEnocunterDateTime.size() != 0)) {

                                                    if (((maxEnocunterDateTime.get(0)
                                                            .getTime()) >= threeMonthsBeforeEndDate.getTime()
                                                            && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                                                                    .getTime())) {

                                                        patientsNotLostToFollowUp.add(patientId);

                                                    }

                                                    else {

                                                        indicator++;
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }
                            }

                            if (HivTestResultConcept.get(0) == Integer
                                    .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                SQLQuery queryTestingStatusOfPartner = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "where ob.concept_id = "
                                                + Integer.parseInt(
                                                        GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                + " and pg.patient_id = " + patientId);

                                List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner.list();

                                if (patientIdsTestingStatusOfPartner.size() != 0) {

                                    SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                            .list();

                                    if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                .createSQLQuery(
                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetTestingStatusOfPartnerConceptId())
                                                                + " and o.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                + HivTestResultDate.get(0)
                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                + patientId);
                                        List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                .size() != 0) {

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .get(0) == Integer.parseInt(GlobalProperties
                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                        "select distinct rel.person_b from relationship rel "
                                                                + " inner join person pe on rel.person_b = pe.person_id "
                                                                + " inner join encounter en on rel.person_b = en.patient_id "
                                                                + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                + " where rel.person_a = " + patientId
                                                                + " and pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and pg.voided = 0 and rel.voided = 0 and rel.person_a = "
                                                                + patientId);

                                                List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                                if (infantHIVPositive.size() != 0) {

                                                    for (Integer patientIdsInfant : infantHIVPositive) {

                                                        SQLQuery queryInfantExited = session.createSQLQuery(
                                                                "select distinct o.person_id from obs o where o.concept_id = "
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetExitFromCareConceptId())
                                                                        + "  and (cast(o.obs_datetime as DATE)) <= '"
                                                                        + endDate + "'"
                                                                        + " and o.voided = 0 and o.person_id="
                                                                        + patientIdsInfant);

                                                        List<Integer> patientIds2InfantExited = queryInfantExited
                                                                .list();

                                                        if (patientIds2InfantExited.size() == 0) {

                                                            SQLQuery queryDate1 = session.createSQLQuery(
                                                                    "select cast(max(encounter_datetime)as DATE) from encounter where "
                                                                            + "(select(cast(max(encounter_datetime)as Date))) <= '"
                                                                            + endDate
                                                                            + "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                                                                            + patientIdsInfant);

                                                            List<Date> maxEnocunterDateTime = queryDate1.list();

                                                            SQLQuery queryDate2 = session.createSQLQuery(
                                                                    "select cast(max(value_datetime) as DATE ) "
                                                                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                                                            + endDate + "' and concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetReturnVisitDateConceptId())
                                                                            + " and (select(cast(max(value_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                                                            + patientIdsInfant);

                                                            List<Date> maxReturnVisitDay = queryDate2.list();

                                                            if (((maxReturnVisitDay.get(0)) != null)
                                                                    && (maxEnocunterDateTime.size() != 0)) {

                                                                if (((maxEnocunterDateTime.get(0)
                                                                        .getTime()) >= threeMonthsBeforeEndDate
                                                                                .getTime()
                                                                        && (maxEnocunterDateTime.get(0)
                                                                                .getTime()) <= newEndDate.getTime())
                                                                        || ((maxReturnVisitDay.get(0)
                                                                                .getTime()) >= threeMonthsBeforeEndDate
                                                                                        .getTime()
                                                                                && (maxReturnVisitDay.get(0)
                                                                                        .getTime()) <= newEndDate
                                                                                                .getTime())) {

                                                                    patientsNotLostToFollowUp.add(patientId);

                                                                }

                                                                else {

                                                                    indicator++;
                                                                }
                                                            }

                                                            else if ((maxReturnVisitDay.size() == 0)
                                                                    && (maxEnocunterDateTime.size() != 0)) {

                                                                if (((maxEnocunterDateTime.get(0)
                                                                        .getTime()) >= threeMonthsBeforeEndDate
                                                                                .getTime()
                                                                        && (maxEnocunterDateTime.get(0)
                                                                                .getTime()) <= newEndDate
                                                                                        .getTime())) {

                                                                    patientsNotLostToFollowUp.add(patientId);

                                                                }

                                                                else {

                                                                    indicator++;
                                                                }
                                                            }
                                                        }
                                                    }

                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersMalnourished(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int infantHivPosMothersMalnourished(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersScreenedTbThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersScreenedTbThisMonth(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and rel.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetTBScreeningConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetTBScreeningConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        indicator++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and rel.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetTBScreeningConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetTBScreeningConceptId())
                                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        indicator++;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedAt18Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersTestedAt18Months(String startDate, String endDate) throws ParseException {
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0) + "' and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt18MonthId())
                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                    + startDate
                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery QueryInfantInPMTCTTestedAt18Months = session
                                                        .createSQLQuery(
                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                        + " where pg.program_id ="
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetPMTCTProgramId())
                                                                        + " and en.encounter_type = "
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetSerologyAt18MonthId())
                                                                        + " and (select(cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                        + patientIdsInfant);

                                                List<Date> infantInPMTCTTestedAt18Months = QueryInfantInPMTCTTestedAt18Months
                                                        .list();

                                                if (infantInPMTCTTestedAt18Months.size() != 0) {

                                                    if ((infantInPMTCTTestedAt18Months.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (infantInPMTCTTestedAt18Months.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        indicator++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetSerologyAt18MonthId())
                                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery QueryInfantInPMTCTTestedAt18Months = session
                                                                        .createSQLQuery(
                                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                                        + " where pg.program_id ="
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId())
                                                                                        + " and en.encounter_type = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetSerologyAt18MonthId())
                                                                                        + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Date> infantInPMTCTTestedAt18Months = QueryInfantInPMTCTTestedAt18Months
                                                                        .list();

                                                                if (infantInPMTCTTestedAt18Months.size() != 0) {

                                                                    if ((infantInPMTCTTestedAt18Months.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (infantInPMTCTTestedAt18Months.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        indicator++;
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedAt6Weeks(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersTestedAt6Weeks(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPCREncounterId())
                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                    + startDate
                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery QueryInfantInPMTCTTestedAt6Weeks = session.createSQLQuery(
                                                        "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                + " where pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and en.encounter_type = "
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPCREncounterId())
                                                                + " and (select(cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                + patientIdsInfant);

                                                List<Date> infantInPMTCTTestedAt6Weeks = QueryInfantInPMTCTTestedAt6Weeks
                                                        .list();

                                                if (infantInPMTCTTestedAt6Weeks.size() != 0) {

                                                    if ((infantInPMTCTTestedAt6Weeks.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (infantInPMTCTTestedAt6Weeks.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        indicator++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPCREncounterId())
                                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery QueryInfantInPMTCTTestedAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                                        + " where pg.program_id ="
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId())
                                                                                        + " and en.encounter_type = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPCREncounterId())
                                                                                        + " and (select(cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Date> infantInPMTCTTestedAt6Weeks = QueryInfantInPMTCTTestedAt6Weeks
                                                                        .list();

                                                                if (infantInPMTCTTestedAt6Weeks.size() != 0) {

                                                                    if ((infantInPMTCTTestedAt6Weeks.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (infantInPMTCTTestedAt6Weeks.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        indicator++;
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedAt9Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersTestedAt9Months(String startDate, String endDate) throws ParseException {
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt9MonthId())
                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                    + startDate
                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery QueryInfantInPMTCTTestedAt9Months = session.createSQLQuery(
                                                        "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                + " where pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and en.encounter_type = "
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetSerologyAt9MonthId())
                                                                + " and (select(cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                + patientIdsInfant);

                                                List<Date> infantInPMTCTTestedAt9Months = QueryInfantInPMTCTTestedAt9Months
                                                        .list();

                                                if (infantInPMTCTTestedAt9Months.size() != 0) {

                                                    if ((infantInPMTCTTestedAt9Months.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (infantInPMTCTTestedAt9Months.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        indicator++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetSerologyAt9MonthId())
                                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery QueryInfantInPMTCTTestedAt9Months = session
                                                                        .createSQLQuery(
                                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                                        + " where pg.program_id ="
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId())
                                                                                        + " and en.encounter_type = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetSerologyAt9MonthId())
                                                                                        + " and (select(cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Date> infantInPMTCTTestedAt9Months = QueryInfantInPMTCTTestedAt9Months
                                                                        .list();

                                                                if (infantInPMTCTTestedAt9Months.size() != 0) {

                                                                    if ((infantInPMTCTTestedAt9Months.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (infantInPMTCTTestedAt9Months.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        indicator++;
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedPosAt18Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersTestedPosAt18Months(String startDate, String endDate) throws ParseException {
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt18MonthId())
                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt18Months = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetResultForHIVTestConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate + "' and ob.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt18Months = queryInfantTestedPCRPosAt18Months
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt18Months.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetResultForHIVTestConceptId())
                                                                            + " and o.value_coded in ("
                                                                            + GlobalProperties
                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                .createSQLQuery(
                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                + Integer.parseInt(GlobalProperties
                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                + " and o.value_coded in ("
                                                                                + GlobalProperties
                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                + HivTestResultDate.get(0)
                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                + patientIdsInfant);
                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                .list();

                                                        if (HIVResultConceptForInfantTested.size() != 0) {

                                                            if (HIVResultConceptForInfantTested.get(0) == Integer
                                                                    .parseInt(GlobalProperties
                                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                indicator++;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPCREncounterId())
                                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and ob.value_coded in ("
                                                                                        + GlobalProperties
                                                                                                .gpGetListOfAnswersToResultOfHIVTest()
                                                                                        + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + "   and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetResultForHIVTestConceptId())
                                                                                            + " and o.value_coded in ("
                                                                                            + GlobalProperties
                                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                                .createSQLQuery(
                                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                                + Integer.parseInt(
                                                                                                        GlobalProperties
                                                                                                                .gpGetResultForHIVTestConceptId())
                                                                                                + " and o.value_coded in ("
                                                                                                + GlobalProperties
                                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                                + HivTestResultDate
                                                                                                        .get(0)
                                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                                + patientIdsInfant);
                                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                                .list();

                                                                        if (HIVResultConceptForInfantTested
                                                                                .size() != 0) {

                                                                            if (HIVResultConceptForInfantTested
                                                                                    .get(0) == Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                                indicator++;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedPosAt6Weeks(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersTestedPosAt6Weeks(String startDate, String endDate) throws ParseException {
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPCREncounterId())
                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetResultForHIVTestConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate + "' and ob.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetResultForHIVTestConceptId())
                                                                            + " and o.value_coded in ("
                                                                            + GlobalProperties
                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                .createSQLQuery(
                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                + Integer.parseInt(GlobalProperties
                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                + " and o.value_coded in ("
                                                                                + GlobalProperties
                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                + HivTestResultDate.get(0)
                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                + patientIdsInfant);

                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                .list();

                                                        if (HIVResultConceptForInfantTested.size() != 0) {

                                                            if (HIVResultConceptForInfantTested.get(0) == Integer
                                                                    .parseInt(GlobalProperties
                                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                indicator++;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPCREncounterId())
                                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and ob.value_coded in ("
                                                                                        + GlobalProperties
                                                                                                .gpGetListOfAnswersToResultOfHIVTest()
                                                                                        + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetResultForHIVTestConceptId())
                                                                                            + " and o.value_coded in ("
                                                                                            + GlobalProperties
                                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                                .createSQLQuery(
                                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                                + Integer.parseInt(
                                                                                                        GlobalProperties
                                                                                                                .gpGetResultForHIVTestConceptId())
                                                                                                + " and o.value_coded in ("
                                                                                                + GlobalProperties
                                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                                + HivTestResultDate
                                                                                                        .get(0)
                                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                                + patientIdsInfant);
                                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                                .list();

                                                                        if (HIVResultConceptForInfantTested
                                                                                .size() != 0) {

                                                                            if (HIVResultConceptForInfantTested
                                                                                    .get(0) == Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                                indicator++;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedPosAt9Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivPosMothersTestedPosAt9Months(String startDate, String endDate) throws ParseException {
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPCREncounterId())
                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetResultForHIVTestConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate + "' and ob.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetResultForHIVTestConceptId())
                                                                            + " and o.value_coded in ("
                                                                            + GlobalProperties
                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                .createSQLQuery(
                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                + Integer.parseInt(GlobalProperties
                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                + " and o.value_coded in ("
                                                                                + GlobalProperties
                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                + HivTestResultDate.get(0)
                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                + patientIdsInfant);
                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                .list();

                                                        if (HIVResultConceptForInfantTested.size() != 0) {

                                                            if (HIVResultConceptForInfantTested.get(0) == Integer
                                                                    .parseInt(GlobalProperties
                                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                indicator++;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select(cast(max(o.obs_datetime)as DATE))) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPCREncounterId())
                                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and ob.value_coded in ("
                                                                                        + GlobalProperties
                                                                                                .gpGetListOfAnswersToResultOfHIVTest()
                                                                                        + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetResultForHIVTestConceptId())
                                                                                            + " and o.value_coded in ("
                                                                                            + GlobalProperties
                                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                                .createSQLQuery(
                                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                                + Integer.parseInt(
                                                                                                        GlobalProperties
                                                                                                                .gpGetResultForHIVTestConceptId())
                                                                                                + " and o.value_coded in ("
                                                                                                + GlobalProperties
                                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                                + HivTestResultDate
                                                                                                        .get(0)
                                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                                + patientIdsInfant);
                                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                                .list();

                                                                        if (HIVResultConceptForInfantTested
                                                                                .size() != 0) {

                                                                            if (HIVResultConceptForInfantTested
                                                                                    .get(0) == Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                                indicator++;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTherapFood(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int infantHivPosMothersTherapFood(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newInfantHivPosMothersNvpAztAtBirth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int newInfantHivPosMothersNvpAztAtBirth(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#reportedDeadInfantHivPosMothers(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int reportedDeadInfantHivPosMothers(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'" + " and o.person_id="
                                + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantDied = session.createSQLQuery(
                                                    "select distinct pg.patient_id from patient_program pg "
                                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                            + "where ob.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                            + startDate
                                                            + "' and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and ob.value_coded = "
                                                            + GlobalProperties.gpGetExitFromCareDiedConceptId()
                                                            + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                            + " and pg.patient_id = " + patientIdsInfant);

                                            List<Integer> patientIdsQueryInfantDied = queryInfantDied.list();

                                            if (patientIdsQueryInfantDied.size() != 0) {

                                                SQLQuery queryHIVResultDateForInfantDied = session.createSQLQuery(
                                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetExitFromCareConceptId())
                                                                + " and o.value_coded = "
                                                                + GlobalProperties.gpGetExitFromCareDiedConceptId()
                                                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                + endDate
                                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                + patientIdsInfant);

                                                List<Date> HIVResultDateForInfantDied = queryHIVResultDateForInfantDied
                                                        .list();

                                                if (HIVResultDateForInfantDied.size() != 0) {

                                                    if ((HIVResultDateForInfantDied.get(0).getTime() >= newStartDate
                                                            .getTime())
                                                            && (HIVResultDateForInfantDied.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        indicator++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (HivTestResultConcept.get(0) == Integer
                                    .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                SQLQuery queryTestingStatusOfPartner = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "where ob.concept_id = "
                                                + Integer.parseInt(
                                                        GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                + " and pg.patient_id = " + patientId);

                                List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner.list();

                                if (patientIdsTestingStatusOfPartner.size() != 0) {

                                    SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                            .list();

                                    if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                .createSQLQuery(
                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetTestingStatusOfPartnerConceptId())
                                                                + " and o.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                + HivTestResultDate.get(0)
                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                + patientId);
                                        List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                .size() != 0) {

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .get(0) == Integer.parseInt(GlobalProperties
                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                        "select distinct rel.person_b from relationship rel "
                                                                + " inner join person pe on rel.person_b = pe.person_id "
                                                                + " inner join encounter en on rel.person_b = en.patient_id "
                                                                + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                + " where rel.person_a = " + patientId
                                                                + " and pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                + patientId);

                                                List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                                if (infantHIVPositive.size() != 0) {

                                                    for (Integer patientIdsInfant : infantHIVPositive) {

                                                        SQLQuery queryInfantDied = session.createSQLQuery(
                                                                "select distinct pg.patient_id from patient_program pg "
                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                        + "where ob.concept_id = "
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetExitFromCareConceptId())
                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                        + startDate
                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                        + endDate + "' and ob.value_coded = "
                                                                        + GlobalProperties
                                                                                .gpGetExitFromCareDiedConceptId()
                                                                        + " and (cast(pg.date_enrolled as DATE)) <= '"
                                                                        + endDate
                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                        + " and pg.patient_id = "
                                                                        + patientIdsInfant);

                                                        List<Integer> patientIdsQueryInfantDied = queryInfantDied
                                                                .list();

                                                        if (patientIdsQueryInfantDied.size() != 0) {

                                                            SQLQuery queryHIVResultDateForInfantDied = session
                                                                    .createSQLQuery(
                                                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                    + Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetExitFromCareConceptId())
                                                                                    + " and o.value_coded = "
                                                                                    + GlobalProperties
                                                                                            .gpGetExitFromCareDiedConceptId()
                                                                                    + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                    + endDate
                                                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.value and o.person_id="
                                                                                    + patientIdsInfant);

                                                            List<Date> HIVResultDateForInfantDied = queryHIVResultDateForInfantDied
                                                                    .list();

                                                            if ((HIVResultDateForInfantDied.get(0)
                                                                    .getTime() >= newStartDate.getTime())
                                                                    && (HIVResultDateForInfantDied.get(0)
                                                                            .getTime() <= newEndDate.getTime())) {

                                                                indicator++;

                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosBreastFeeding(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosBreastFeeding(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select cast(encounter_datetime as DATE)) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds4 = query3.list();

                            if (patientIds4.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            SQLQuery queryHIVPosWomenBreastFeeding = session.createSQLQuery(
                                                    "select distinct pg.patient_id from patient_program pg "
                                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                            + "where ob.concept_id = "
                                                            + Integer.parseInt(GlobalProperties
                                                                    .gpGetInfantFeedingMethodConceptId())
                                                            + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                            + startDate
                                                            + "' and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and ob.value_coded IN ("
                                                            + GlobalProperties
                                                                    .gpGetBreastedPredominatelyConceptIdConceptId()
                                                            + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                            + endDate
                                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                            + " and pg.patient_id = " + patientId);

                                            List<Integer> patientIdsOfHIVPosWomenBreastFeeding = queryHIVPosWomenBreastFeeding
                                                    .list();

                                            if (patientIdsOfHIVPosWomenBreastFeeding.size() != 0)

                                            {

                                                indicator++;

                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosUsingFormula(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosUsingFormula(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select cast(encounter_datetime as DATE)) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds4 = query3.list();

                            if (patientIds4.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            SQLQuery queryHIVPosWomenBreastFeeding = session.createSQLQuery(
                                                    "select distinct pg.patient_id from patient_program pg "
                                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                            + "where ob.concept_id = "
                                                            + Integer.parseInt(GlobalProperties
                                                                    .gpGetInfantFeedingMethodConceptId())
                                                            + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                            + startDate
                                                            + "' and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and ob.value_coded IN ("
                                                            + GlobalProperties
                                                                    .gpGetBreastedPredominatelyConceptIdConceptId()
                                                            + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                            + endDate
                                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                            + " and pg.patient_id = " + patientId);

                                            List<Integer> patientIdsOfHIVPosWomenBreastFeeding = queryHIVPosWomenBreastFeeding
                                                    .list();

                                            if (patientIdsOfHIVPosWomenBreastFeeding.size() != 0)

                                            {

                                                indicator++;

                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    // ----------D. Family Planning Data Elements-------------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosExpectedFpAtFacility(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosExpectedFpAtFacility(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personExpectedAtFacilityIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetEstimatedDateOfCOnfinementId())
                            + "' AND (cast(ob.value_datetime as DATE)) >= '" + startDate + "'"
                            + " AND (cast(ob.value_datetime as DATE)) <= '" + endDate + "' ")
                    .list();
            List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId()) + "' ")
                    .list();
            List<Integer> patientInEncounterIds = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                    .list();

            for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
                for (Integer personExpectedAtFacilityId : personExpectedAtFacilityIds) {
                    if (personExpectedAtFacilityId.equals(personFemaleWithHIVPosId))
                        for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                            for (Integer patientInEncounterId : patientInEncounterIds) {

                                if (personExpectedAtFacilityId.equals(patientInEncounterId)
                                        && personExpectedAtFacilityId.equals(personFemaleWithHIVPosId)
                                        && personExpectedAtFacilityId.equals(personInFamilyPlanningId)) {
                                    indicator++;
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosSeenInFp(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosSeenInFp(String startDate, String endDate) {
        // TODO Auto-generated method stub
        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> patientInEncounterIds = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                    .list();
            List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId())
                            + "' AND (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                            + " AND (cast(ob.obs_datetime as DATE)) <= '" + endDate + "' ")
                    .list();

            for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
                for (int patientInProgramId : patientInProgramIds) {
                    if (personFemaleWithHIVPosId.equals(patientInProgramId))

                        for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                            for (int patientInEncounterId : patientInEncounterIds) {

                                if (personInFamilyPlanningId.equals(personFemaleWithHIVPosId)
                                        && personInFamilyPlanningId.equals(patientInProgramId)
                                        && personInFamilyPlanningId.equals(patientInEncounterId)) {
                                    indicator++;
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of HIV positive women partners seen in family planning
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosPartnersSeenInFp(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosPartnersSeenInFp(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId())
                            + "' AND (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                            + " AND (cast(ob.obs_datetime as DATE)) <= '" + endDate + "' ")
                    .list();
            List<Integer> partnerInFamilyPlanningIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetTestingStatusOfPartnerId())
                            + "' AND (cast(o.obs_datetime as DATE)) <= '" + endDate + "' ")
                    .list();
            List<Integer> patientEncounterIds = session.createSQLQuery(
                    "select distinct pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id")
                    .list();

            for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
                for (Integer personInProgramId : patientInProgramIds) {
                    if (personInProgramId.equals(personFemaleWithHIVPosId))
                        for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                            for (Integer partnerInFamilyPlanningId : partnerInFamilyPlanningIds) {
                                if (personInFamilyPlanningId.equals(partnerInFamilyPlanningId))
                                    for (Integer patientEncounterId : patientEncounterIds) {

                                        if (personInProgramId.equals(personFemaleWithHIVPosId)
                                                && personInProgramId.equals(patientEncounterId)
                                                && personInProgramId.equals(personInFamilyPlanningId)
                                                && personInProgramId.equals(partnerInFamilyPlanningId)) {

                                            indicator++;
                                        }
                                    }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosReceivingModernContraceptive(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosReceivingModernContraceptive(String startDate, String endDate) {
        // TODO Auto-generated method stub
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                            + "' and p.voided=false")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate
                            + "' AND pp.date_completed is null ")
                    .list();
            List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetInjectableContraceptivesId())
                            + "' or o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetOralContraceptionId())
                            + "' or o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetCondomsId())
                            + "' AND (cast(o.obs_datetime as DATE)) >= '" + startDate + "'"
                            + " AND (cast(o.obs_datetime as DATE)) <= '" + endDate + "' ")
                    .list();
            List<Integer> patientEncounterIds = session.createSQLQuery(
                    "select distinct pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id")
                    .list();

            for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
                for (Integer patientInProgramId : patientInProgramIds)
                    if (patientInProgramId.equals(personFemaleWithHIVPosId))
                        for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                            for (Integer patientEncounterId : patientEncounterIds) {

                                if (patientInProgramId.equals(personFemaleWithHIVPosId)
                                        && patientInProgramId.equals(patientEncounterId)
                                        && patientInProgramId.equals(personInFamilyPlanningId)) {
                                    indicator++;
                                }
                            }
                        }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosRefferedForFp(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int womenHivPosRefferedForFp(String startDate, String endDate) {
        // TODO Auto-generated method stub
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                            + "' and p.voided=false ")
                    .list();
            List<Integer> personReferredForFpIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetDispositionId()) + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetReferredForFamilyPlanningId())
                            + "' AND (cast(o.obs_datetime as DATE)) >= '" + startDate + "'"
                            + " AND (cast(o.obs_datetime as DATE)) <= '" + endDate + "' ")
                    .list();
            List<Integer> patientEncounterIds = session.createSQLQuery(
                    "select distinct pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id")
                    .list();
            for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
                for (Integer personReferredForFp : personReferredForFpIds) {
                    if (personReferredForFp.equals(personFemaleWithHIVPosId))
                        for (Integer patientEncounterId : patientEncounterIds)
                            if (personReferredForFp.equals(personFemaleWithHIVPosId)
                                    && personReferredForFp.equals(patientEncounterId)) {
                                indicator++;
                            }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;
    }

    // ---------E. Submit VCT Data Elements-----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#couplesCounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int couplesCounseledTested(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personCoupledIds = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling=2 and p.voided=false and t.date_registration between '"
                            + startDate + "' AND '" + endDate
                            + "' AND p.gender='M' and p.voided = 0 and t.voided = 0 ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0 ")
                    .list();

            for (Integer personCoupledId : personCoupledIds) {
                for (Integer personTestedId : personTested) {
                    if (personTestedId.equals(personCoupledId))

                        indicator++;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#discordantCouples2(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int discordantCouples2(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> coupleCounseledTestedIds = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id inner join trac_sample_test ts on t.code_test=ts.sample_code where ts.voided=0 and t.vct_or_pit=0 and t.type_of_counseling=2 and p.voided=false and t.partner_id is not null ")
                    .list();

            List<Integer> discordantCoupleMalePartnerIds = session.createSQLQuery(
                    "select distinct t.client_id from trac_vct_client t inner join obs o on t.client_id-o.person_id where o.concept_id='2169' and o.value_coded='664' ")
                    .list();
            List<Integer> discordantCoupleMaleInfectedIds = session.createSQLQuery(
                    "Select distinct t.partner_id from trac_vct_client t inner join obs o on t.client_id=o.person_id where o.concept_id='2169' and o.value_coded='703' ")
                    .list();

            // List<Integer>discordantCoupleFemalePartnerInfectedIds=session.createSQLQuery("select distinct t.client_id from trac_vct_client t inner join obs o on t.client_id-o.person_id where o.concept_id='2169' and o.value_coded='703' ").list();
            // List<Integer>discordantCoupleFemaleInfectedIds=session.createSQLQuery("Select distinct t.partner_id from trac_vct_client t inner join obs o on t.client_id=o.person_id where o.concept_id='2169' and o.value_coded='664' ").list();

            for (Integer coupleCounseledTestedId : coupleCounseledTestedIds) {
                for (Integer discordantCoupleMalePartnerId : discordantCoupleMalePartnerIds) {
                    for (Integer discordantCoupleMaleInfectedId : discordantCoupleMaleInfectedIds) {
                        if (coupleCounseledTestedId.equals(discordantCoupleMalePartnerId)
                                && coupleCounseledTestedId.equals(discordantCoupleMaleInfectedId)) {

                            // for (Integer
                            // discordantCoupleFemalePartnerInfectedId:discordantCoupleFemalePartnerInfectedIds){
                            // for(Integer
                            // discordantCoupleFemaleInfectedId:discordantCoupleFemaleInfectedIds)
                            // {

                            indicator++;
                        }
                    }
                }
            }
            // }
            // }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleHivPosMoreThan25(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleHivPosMoreThan25(String startDate, String endDate) {

        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided= 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleHivPosUnder15to24(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleHivPosUnder15to24(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "',pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',pe.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of HIV positive female clients (age<15)
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleHivPosUnderFifteen(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleHivPosUnderFifteen(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 and pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleHivPosMoreThan25(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleHivPosMoreThan25(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestedId)
                                    && personReceivedResultId.equals(personMaleId)) {

                                indicator++;

                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleHivPosUnder15to24(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleHivPosUnder15to24(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "',pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',pe.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleHivPosUnderFifteen(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleHivPosUnderFifteen(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided =0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestedId)
                                    && personReceivedResultId.equals(personMaleId)) {

                                indicator++;
                            }

                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new female clients(age 15-24) tested and received result
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemale15To24TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemale15To24TestReceiveRes(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided=0 and o.voided = 0 and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personFemaleId))
                        for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                            if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                    && personTestedAndReceivedResultId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleFifteenTo24CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleFifteenTo24CounseledTested(String startDate, String endDate) {
        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided= 0 and o.voided = 0 ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Number of new Female clients (age 25+) counseled and tested for HIV
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleMore25CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleMore25CounseledTested(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleMore25TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleMore25TestReceiveRes(String startDate, String endDate) {

        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                    if (personCounseledAndTestsedId.equals(personFemaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                    && personReceivedResultId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleUnderFifteenCounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleUnderFifteenCounseledTested(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleUnderFifteenTestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newFemaleUnderFifteenTestReceiveRes(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new male clients(age 15-24) tested and received result
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMale15To24TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMale15To24TestReceiveRes(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                            if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                    && personTestedAndReceivedResultId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleFifteenTo24CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleFifteenTo24CounseledTested(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided= 0 and o.voided = 0 ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleMore25CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleMore25CounseledTested(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' ")
                    .list();
            // List<Integer> personCounseled = session
            // .createSQLQuery(
            // "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling=1 and t.date_registration between '"
            // + startDate + "' AND '" + endDate + "' ")
            // .list();

            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();

            // List<Integer> personTested = session
            // .createSQLQuery(
            // "SELECT distinct t.client_id from trac_vct_client t inner join trac_sample_test ts on t.code_test=ts.sample_code where ts.voided=0")
            // .list();

            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Number of new male clients (age 25+)tested and receiver results
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleMore25TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleMore25TestReceiveRes(String startDate, String endDate) {

        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                    if (personCounseledAndTestsedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                    && personReceivedResultId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleUnderFifteenCounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleUnderFifteenCounseledTested(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleUnderFifteenTestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newMaleUnderFifteenTestReceiveRes(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestedId)
                                    && personReceivedResultId.equals(personMaleId)) {

                                indicator++;

                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    // ----------F. Provider-Initiated Testing (PIT) Data Elements-----------

    /**
     * Number of new female clients (ages 15-24) Counseled and tested for hiv
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#female15To24CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int female15To24CounseledThroughPit(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided= 0 and o.voided = 0 ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#female15To24HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int female15To24HivPosThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "',pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',pe.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new female client (age 15-24)tested HIV positive through PIT
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#female15To24HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int female15To24HivResThroughPit(String startDate, String endDate) {

        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personFemaleId))
                        for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                            if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                    && personTestedAndReceivedResultId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThan25CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleMoreThan25CounseledThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThan25HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleMoreThan25HivPosThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThan25HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleMoreThan25HivResThroughPit(String startDate, String endDate) {

        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                    if (personCounseledAndTestsedId.equals(personFemaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                    && personReceivedResultId.equals(personFemaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleUnderFifteenCounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleUnderFifteenCounseledThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', p.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND p.voided = 0 and o.voided = 0 AND p.gender = 'M' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleUnderFifteenHivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleUnderFifteenHivPosThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleUnderFifteenHivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int femaleUnderFifteenHivResThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personFemaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0 ")
                    .list();

            for (Integer personFemaleId : personFemaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personFemaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#male15To24CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int male15To24CounseledThroughPit(String startDate, String endDate) {
        // TODO Auto-generated method stub
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided = 0 and o.voided = 0 ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#male15To24HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int male15To24HivPosThroughPit(String startDate, String endDate) {

        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "',pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',pe.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t inner join trac_sample_test ts on t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#male15To24HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int male15To24HivResThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                            + endDate + "',p.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId()) + " and DATEDIFF('" + endDate
                            + "',p.birthdate) <= " + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                            + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                            if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                    && personTestedAndReceivedResultId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThan25CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleMoreThan25CounseledThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new male clients (age 25+) tested for HIV positive through PIT
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThan25HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleMoreThan25HivPosThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestedId)
                                    && personReceivedResultId.equals(personMaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThan25HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleMoreThan25HivResThroughPit(String startDate, String endDate) {

        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) >= "
                            + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                    if (personCounseledAndTestsedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                    && personReceivedResultId.equals(personMaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleUnderFifteenCounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleUnderFifteenCounseledThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', p.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND p.voided = 0 and o.voided = 0 AND p.gender = 'M' ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;

                            }
                        }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleUnderFifteenHivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleUnderFifteenHivPosThroughPit(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personReceivedResultIds = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                    if (personCounseledAndTestedId.equals(personMaleId))
                        for (Integer personReceivedResultId : personReceivedResultIds) {
                            if (personReceivedResultId.equals(personCounseledAndTestedId)
                                    && personReceivedResultId.equals(personMaleId)) {
                                indicator++;
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new females (age <15) who received HIV results through PIT
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleUnderFifteenHivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int maleUnderFifteenHivResThroughPit(String startDate, String endDate) {
        // TODO Auto-generated method stub
        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personMaleIds = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                            + endDate + "', pe.birthdate) < "
                            + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                            + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                    .list();
            List<Integer> personCounseled = session.createSQLQuery(
                    "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                            + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personTested = session.createSQLQuery(
                    "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0 ")
                    .list();

            for (Integer personMaleId : personMaleIds) {
                for (Integer personCounseledId : personCounseled) {
                    if (personCounseledId.equals(personMaleId))
                        for (Integer personTestedId : personTested) {
                            if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                                indicator++;
                            }
                        }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    // ----------G. PEP Data Elements----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOccupExpo3MonthAfterPep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivOccupExpo3MonthAfterPep(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();

            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                    "SELECT  DISTINCT enc.patient_id FROM encounter enc inner join obs ob on ob.person_id=enc.patient_id where ob.concept_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'")
                    .list();
            List<Integer> personAtRiskExposedIds = session.createSQLQuery(
                    "SELECT DISTINCT p.patient_id from patient p inner join obs o on p.patient_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetExposureToBloodOrBloodProductId()) + "' ")
                    .list();
            List<Integer> personOnArvDrugIds = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                            + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                            + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                    .list();

            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
                    if (personEnrolledInPepId.equals(personEnrolledInPepPRogramAtRiskOfOcupationExposureId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                if (patientInProgramId.equals(personOnEncountersWithId))
                                    for (Integer personAtRiskExposedId : personAtRiskExposedIds) {
                                        for (Integer personOnArvDrugId : personOnArvDrugIds) {
                                            if ((personEnrolledInPepId
                                                    .equals(personEnrolledInPepPRogramAtRiskOfOcupationExposureId)
                                                    && personEnrolledInPepId.equals(patientInProgramId))
                                                    && personEnrolledInPepId.equals(personOnEncountersWithId)
                                                    && personEnrolledInPepId.equals(personAtRiskExposedId)
                                                    && personEnrolledInPepId.equals(personOnArvDrugId)) {

                                                indicator++;
                                            }
                                        }
                                    }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOccupationExposure(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivOccupationExposure(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> patientInEncounterIds = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                    .list();
            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetExposureToBloodOrBloodProductId()) + "' ")
                    .list();

            for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
                for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                    if (personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                                for (Integer patientInEncounterId : patientInEncounterIds) {

                                    if ((personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                            .equals(personEnrolledInPepId)
                                            && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                    .equals(patientInEncounterId)
                                            && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                    .equals(patientInProgramId))
                                            && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                    .equals(personAtRiskOnPEPId)) {

                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of
     * occupational exposure who received PEP
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOccupationExposurePep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivOccupationExposurePep(String startDate, String endDate) {
        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp inner join encounter enc on pp.patient_id=enc.patient_id")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                    "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetExposureToBloodOrBloodProductId()) + "' ")
                    .list();
            List<Integer> personOnArvDrug = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                            + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                            + " AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                    .list();

            for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
                for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                    if (personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                                if (patientInProgramId.equals(personAtRiskOnPEPId))
                                    for (Integer personOnArvDrugId : personOnArvDrug) {
                                        for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                            if ((personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                    .equals(personEnrolledInPepId)
                                                    && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                            .equals(patientInProgramId))
                                                    && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                            .equals(personAtRiskOnPEPId)
                                                    && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                            .equals(personOnArvDrugId)
                                                    && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                            .equals(personOnEncountersWithId)) {

                                                indicator++;
                                            }
                                        }
                                    }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOtherNoneOccupExpo3MonthAfterPep(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int newAtRiskHivOtherNoneOccupExpo3MonthAfterPep(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOtherNoneOccupationExposure(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivOtherNoneOccupationExposure(String startDate, String endDate) {
        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personEnrolledInPepPRogramAtRiskOfNonOcupationExposureIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> patientInEncounterIds = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                    .list();
            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetSexualContactWithHivPositivePatient()) + "' ")
                    .list();

            for (Integer personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId : personEnrolledInPepPRogramAtRiskOfNonOcupationExposureIds) {
                for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                    if (personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId.equals(personEnrolledInPepId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                                for (Integer patientInEncounterId : patientInEncounterIds) {

                                    if ((personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                            .equals(personEnrolledInPepId)
                                            && personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                                    .equals(patientInEncounterId)
                                            && personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                                    .equals(patientInProgramId))
                                            && personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                                    .equals(personAtRiskOnPEPId)) {
                                        indicator++;
                                    }
                                }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of other
     * non-occupational exposure who received PEP
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOtherNoneOccupationExposurePep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivOtherNoneOccupationExposurePep(String startDate, String endDate) {
        int indicator = 0;
        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp inner join encounter enc on pp.patient_id=enc.patient_id")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                    "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='"
                            + Integer.parseInt(GlobalProperties.gpGetSexualContactWithHivPositivePatient()) + "' ")
                    .list();
            List<Integer> personOnArvDrug = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                            + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                            + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                    .list();

            for (Integer personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId : personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureIds) {
                for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                    if (personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId.equals(personEnrolledInPepId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                                if (patientInProgramId.equals(personAtRiskOnPEPId))
                                    for (Integer personOnArvDrugId : personOnArvDrug) {
                                        for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                            if ((personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                    .equals(personEnrolledInPepId)
                                                    && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                            .equals(patientInProgramId))
                                                    && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                            .equals(personAtRiskOnPEPId)
                                                    && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                            .equals(personOnArvDrugId)
                                                    && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                            .equals(personOnEncountersWithId)) {

                                                indicator++;
                                            }
                                        }
                                    }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of rape/
     * sexual assault
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivRapeAssault(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivRapeAssault(String startDate, String endDate) {
        int indicator = 0;

        try {
            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                    "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetSexualAssaultId())
                            + "' ")
                    .list();

            for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
                for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                    if (personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {

                                if ((personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                        .equals(personEnrolledInPepId)
                                        && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                .equals(patientInProgramId))
                                        && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                .equals(personAtRiskOnPEPId)) {

                                    indicator++;
                                }

                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivRapeAssault3MonthAfterPep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivRapeAssault3MonthAfterPep(String startDate, String endDate) {
        int indicator = 0;

        /*
         * Date myDate=null; SimpleDateFormat date=new
         * SimpleDateFormat("yyyy-MM-dd"); try { myDate=date.parse(startDate);
         * 
         * Calendar cal=Calendar.getInstance(); if(myDate!=null)
         * cal.setTime(myDate); cal.add(Calendar.MONTH, -3); Date
         * beforeThreeMonthOfStartDate=cal.getTime();
         */

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                    .list();
            List<Integer> personOnArvDrug = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id = "
                            + ConstantValues.EFAVIRENZ
                            + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null ")
                    .list();

            for (Integer patientInProgramId : patientInProgramIds) {
                for (Integer personOnArvDrugId : personOnArvDrug) {
                    if (patientInProgramId.equals(personOnArvDrugId)) {
                        indicator++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of rape/sexual
     * assault who received PEP
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivRapeAssaultPep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int newAtRiskHivRapeAssaultPep(String startDate, String endDate) {
        int indicator = 0;

        try {

            Session session = getSessionFactory().getCurrentSession();
            List<Integer> personEnrolledInPepPRogramAtRiskOfRapeAssaultIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                    .list();
            List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                    "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                    .list();
            List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp inner join encounter enc on pp.patient_id=enc.patient_id")
                    .list();
            List<Integer> patientInProgramIds = session.createSQLQuery(
                    "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                            + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                            + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                    .list();
            List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                    "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                            + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                            + "' and o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetSexualAssaultId())
                            + "' ")
                    .list();
            List<Integer> personOnArvDrug = session.createSQLQuery(
                    "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                            + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                            + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                    .list();

            for (Integer personEnrolledInPepPRogramAtRiskOfRapeAssaultId : personEnrolledInPepPRogramAtRiskOfRapeAssaultIds) {
                for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                    if (personEnrolledInPepPRogramAtRiskOfRapeAssaultId.equals(personEnrolledInPepId))
                        for (Integer patientInProgramId : patientInProgramIds) {
                            for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                                if (patientInProgramId.equals(personAtRiskOnPEPId))
                                    for (Integer personOnArvDrugId : personOnArvDrug) {
                                        for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                            if ((personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                    .equals(personEnrolledInPepId)
                                                    && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                            .equals(patientInProgramId))
                                                    && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                            .equals(personAtRiskOnPEPId)
                                                    && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                            .equals(personOnArvDrugId)
                                                    && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                            .equals(personOnEncountersWithId)) {

                                                indicator++;
                                            }
                                        }
                                    }
                            }
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    // ***********************************************************************************************
    // This is for displaying the list of patients matching the conditions.
    // ***********************************************************************************************

    // -----------A. PRE-ART Data Elements------------

    /**
     * Number of patients on Cotrimoxazole Prophylaxis this month
     * 
     * @throws ParseException
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#patientsOnCotrimoProphylaxis(java.util.Date,
     *      java.util.Date)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> patientsOnCotrimoProphylaxisList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + " inner join person pe on pg.patient_id = pe.person_id "
                    + " inner join patient pa on pg.patient_id = pa.patient_id "
                    + " inner join orders ord on pg.patient_id = ord.patient_id "
                    + " where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of new pediatric patients (age <18 months) enrolled in HIV
     * care
     * 
     * @throws ParseException
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderEighteenMonthsInHivCare(java.util.Date,
     *      java.util.Date)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsUnderEighteenMonthsInHivCareList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        ArrayList<Person> patients = new ArrayList<Person>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and pg.voided = 0 and pe.voided = 0 "
                    + " and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            patientIdsList.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of female adult patients (age 15 or older) ever enrolled in
     * HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThanFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleMoreThanFifteenEverInHivList(String startDate, String endDate) {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if ((patientIds2.size() == 0)) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of female pediatric patients (age <15 years) ever enrolled
     * in HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femalePedsUnderFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femalePedsUnderFifteenEverInHivList(String startDate, String endDate) {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and pe.gender = 'F' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of male adult patients (age 15 or older) ever enrolled in
     * HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThanFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleMoreThanFifteenEverInHivList(String startDate, String endDate) {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and pe.gender = 'M' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of male pediatric patients (age <15 years) ever enrolled in
     * HIV care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#malePedsUnderFifteenEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> malePedsUnderFifteenEverInHivList(String startDate, String endDate) {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                    + " and pe.gender = 'M' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                        + " and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of newly enrolled patients (age 15+ years) who started TB
     * treatment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newEnrolledAdultsStartTbTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newEnrolledAdultsStartTbTreatThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                    + " and ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryMinStartDate = session
                                .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                        + " inner join drug_order do on ord.order_id = do.order_id "
                                        /*
                                         * +
                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                         */
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                                        + ") "
                                        + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryExited = session
                                    .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                            + " and o.voided = 0 and o.person_id= " + patientId);

                            List<Integer> patientIds3 = queryExited.list();

                            if ((patientIds3.size() == 0)) {

                                patientIdsList.add(patientId);

                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of newly enrolled patients (age <15 years) who started TB
     * treatment this month?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newEnrolledPedsStartTbTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newEnrolledPedsStartTbTreatThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                    + " and ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryMinStartDate = session
                                .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                        + " inner join drug_order do on ord.order_id = do.order_id "
                                        /*
                                         * +
                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                         */
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfTBDrugs()
                                        + ") "
                                        + " and (select(cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                        if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                            SQLQuery queryExited = session
                                    .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                            + " and o.voided = 0 and o.person_id= " + patientId);

                            List<Integer> patientIds3 = queryExited.list();

                            if ((patientIds3.size() == 0)) {

                                patientIdsList.add(patientId);

                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of new female adult patients (age 15+) enrolled in HIV care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleMoreThanFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleMoreThanFifteenInHivCareList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        // Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pg.voided = 0 and pe.voided = 0 "
                    + " and pa.voided = 0 and pe.gender = 'F' and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDateEnrolled = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDateEnrolled.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {
                            patientIdsList.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }

        }

        catch (Exception e) {

            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of new female pediatric patients (age <15 years) enrolled in
     * HIV care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleUnderFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleUnderFifteenInHivCareList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 "
                    + " and pe.gender = 'F' and pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            patientIdsList.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {

            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of new male pediatric patients (age <15 years) enrolled in
     * HIV care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleUnderFifteenInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleUnderFifteenInHivCareList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 "
                    + " and pe.gender = 'M' and pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0  and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            patientIdsList.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of new pediatric patients (age <5 years) enrolled in HIV
     * care?
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderFiveInHivCare(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsUnderFiveInHivCareList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "WHERE ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and pg.voided = 0 and pe.voided = 0 "
                    + " and pa.voided = 0 and pg.date_enrolled >= '" + startDate + "'  and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDate.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {
                        SQLQuery queryTransferredIn = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and o.voided = 0 and o.person_id= " + patientId);

                        List<Integer> patientIds4 = queryTransferredIn.list();

                        if (patientIds4.size() == 0) {

                            patientIdsList.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;

    }

    /**
     * Number of new patients screened for active TB at enrollment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#patientsActiveTbAtEnrolThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> patientsActiveTbAtEnrolThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDateEnrolled = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDateEnrolled.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryExited = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                        + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                        + "' and o.voided = 0 and o.person_id=" + patientId);

                        List<Integer> patientIds3 = queryExited.list();

                        if (patientIds3.size() == 0) {

                            SQLQuery queryDate = session
                                    .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId())
                                            + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfTBScreening = queryDate.list();

                            if (dateOfTBScreening.size() != 0)
                                if ((dateOfTBScreening.get(0).getTime() >= newStartDate.getTime())
                                        && (dateOfTBScreening.get(0).getTime() <= newEndDate.getTime())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of patients screened TB Positive at enrollment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#patientsTbPositiveAtEnrolThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> patientsTbPositiveAtEnrolThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDateEnrolled = session.createSQLQuery(
                        "select cast(min(date_enrolled) as DATE) from patient_program where (select cast(min(date_enrolled) as DATE)) is not null and patient_id = "
                                + patientId);
                List<Date> dateEnrolled = queryDateEnrolled.list();

                if (dateEnrolled.get(0) != null) {

                    if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                            && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryExited = session
                                .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                        + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                        + "' and o.voided = 0 and o.person_id=" + patientId);

                        List<Integer> patientIds3 = queryExited.list();

                        if (patientIds3.size() == 0) {

                            SQLQuery queryDate = session
                                    .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetTBScreeningConceptId())
                                            + " and value_coded= "
                                            + Integer.parseInt(
                                                    GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                                            + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> dateOfTBScreening = queryDate.list();

                            if (dateOfTBScreening.size() != 0)
                                if ((dateOfTBScreening.get(0).getTime() >= newStartDate.getTime())
                                        && (dateOfTBScreening.get(0).getTime() <= newEndDate.getTime())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of pediatric patients (age <18 months) ever enrolled in HIV
     * care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedUnderEighteenMonthsEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pedUnderEighteenMonthsEverInHivList(String startDate, String endDate) {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                    + endDate + "' and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of pediatric patients (age <5 years) ever enrolled in HIV
     * care?
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveEverInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pedsUnderFiveEverInHivList(String startDate, String endDate) {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.date_enrolled <= '"
                    + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.patient_id="
                        + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    // -----------Exporting Data to CSV and Excel Files------------

    /**
     * Exports data to the CSV File or Text File
     * 
     * @throws IOException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToCsvFile(java.util.Map)
     */
    @Override
    public void exportPatientsListToCsvFile(HttpServletRequest request, HttpServletResponse response,
            List<Person> patientsList, String filename, String title, String startDate, String endDate)
            throws IOException {

        Session session = getSessionFactory().getCurrentSession();
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        outputStream.println("" + title + "(Between " + startDate + " and " + endDate + ")");
        outputStream.println();
        outputStream.println("# , Indicator Name , Indicator");
        outputStream.println();
        int count = 0;

        for (Person person : patientsList) {

            Date maxEncounterDateTime = (Date) session
                    .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where patient_id = "
                            + person.getPersonId())
                    .uniqueResult();

            Date maxReturnVisitDay = (Date) session
                    .createSQLQuery("select cast(max(value_datetime) as DATE ) " + "from obs where concept_id = "
                            + ConstantValues.NEXT_SCHEDULED_VISIT + " and person_id = " + person.getPersonId())
                    .uniqueResult();

            count++;
            outputStream.println(count + " , " + person.getPersonId() + " , " + person.getFamilyName() + " "
                    + person.getGivenName() + " , " + person.getGender() + " , " + maxEncounterDateTime.toString()
                    + " , " + maxReturnVisitDay.toString());
        }

        outputStream.flush();
        outputStream.close();
    }

    /**
     * Exports data to the Excel File
     * 
     * @throws IOException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#exportDataToExcelFile(java.util.Map)
     */

    @SuppressWarnings("deprecation")
    @Override
    public void exportPatientsListToExcelFile(HttpServletRequest request, HttpServletResponse response,
            List<Person> patientsList, String filename, String title, String startDate, String endDate)
            throws IOException {

        log.info("exporttttttttttttttttttttttttttttttttttttt" + patientsList);

        Session session = getSessionFactory().getCurrentSession();
        HSSFWorkbook workbook = new HSSFWorkbook();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        HSSFSheet sheet = workbook.createSheet(title);
        int count = 0;
        sheet.setDisplayRowColHeadings(true);

        // Setting Style
        HSSFFont font = workbook.createFont();
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setColor(HSSFFont.COLOR_RED);
        cellStyle.setFillForegroundColor((short) 0xA);

        // Title
        HSSFRow row = sheet.createRow((short) 0);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("");
        row.setRowStyle(cellStyle);
        row.createCell((short) 1).setCellValue("" + title + "(Between " + startDate + " and " + endDate + ")");

        // Headers
        row = sheet.createRow((short) 2);
        row.createCell((short) 0).setCellValue("#");
        row.createCell((short) 1).setCellValue("Patient ID");
        row.createCell((short) 2).setCellValue("Patient Names");
        row.createCell((short) 3).setCellValue("Gender");
        row.createCell((short) 4).setCellValue("Last Encounter Date");
        row.createCell((short) 5).setCellValue("Last Return Visit Date");

        for (Person person : patientsList) {

            // Getting some stuff for Last Encounter Date and Last Return Visit
            // Date.
            Date maxEncounterDateTime = (Date) session
                    .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where patient_id = "
                            + person.getPersonId())
                    .uniqueResult();

            Date maxReturnVisitDay = (Date) session
                    .createSQLQuery("select cast(max(value_datetime) as DATE ) " + "from obs where concept_id = "
                            + ConstantValues.NEXT_SCHEDULED_VISIT + " and person_id = " + person.getPersonId())
                    .uniqueResult();

            count++;
            row = sheet.createRow((short) count + 3);
            row.createCell((short) 0).setCellValue(count);
            row.createCell((short) 1).setCellValue(person.getPersonId());
            row.createCell((short) 2).setCellValue(person.getFamilyName() + " " + person.getGivenName());
            row.createCell((short) 3).setCellValue(person.getGender());
            row.createCell((short) 4).setCellValue(maxEncounterDateTime.toString());
            row.createCell((short) 5).setCellValue(maxReturnVisitDay.toString());
        }
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    // ---------B. ART Data Elements-----------

    /**
     * Total number of adult patients who are on First Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultOnFirstLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> adultOnFirstLineRegList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfFirstLineDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfSecondLineDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of adult patients who are on Second Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultOnSecondLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings({ "unchecked" })
    @Override
    public List<Person> adultOnSecondLineRegList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + "  and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfSecondLineDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.program_id= " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId())
                    + " and pg.date_enrolled <= '" + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of ARV patients (age 15+) who have died this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultDiedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvAdultDiedThisMonthList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                    + " and ord.date_stopped is not null and ord.order_reason = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                                + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfDeath = queryDate.list();

                if (dateOfDeath.size() != 0)
                    if ((dateOfDeath.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfDeath.get(0).getTime() <= newEndDate.getTime())) {

                        patientIdsList.add(patientId);
                    }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age 15+) who have had their treatment interrupted
     * this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultFifteenInterruptTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvAdultFifteenInterruptTreatThisMonthList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and ord.date_stopped is not null and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2Date = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = query2Date.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDrugs = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsPerPatient = queryDrugs.list();

                    SQLQuery queryDrugsDiscontinued = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsDiscontinuedPerPatient = queryDrugsDiscontinued.list();

                    if (drugsPerPatient.get(0) == drugsDiscontinuedPerPatient.get(0)) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(discontinued_date as DATE) from orders ord "
                                        + "inner join drug_order do on ord.order_id = do.order_id "
                                        /*
                                         * +
                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                         */
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                                        + ") and (select cast(discontinued_date as DATE)) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> dateOfDiscontinuedDrugs = queryDate.list();

                        boolean n = true;

                        for (Date d : dateOfDiscontinuedDrugs) {

                            if ((d.getTime() >= newStartDate.getTime()) && (d.getTime() <= newEndDate.getTime())) {
                                ;
                            } else {
                                n = false;
                                break;
                            }

                        }

                        if (n == true) {
                            patientIdsList.add(patientId);
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age 15+) lost to followup (>3 months)
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultLostFollowupMoreThreeMonths(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvAdultLostFollowupMoreThreeMonthsList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate1 = session
                            .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                    + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                    + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                    + patientId);

                    List<Date> maxEnocunterDateTime = queryDate1.list();

                    SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + endDate
                            + "' and concept_id = "
                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                            + patientId);

                    List<Date> maxReturnVisitDay = queryDate2.list();

                    if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            patientIdsList.add(patientId);
                        }
                    }

                    else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            patientIdsList.add(patientId);
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of ARV patients (age 15+) who have been transferred in this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultTransferreInThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvAdultTransferreInThisMonthList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetYesAsAnswerToTransferredInConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2Date = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = query2Date.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateTransferredIn = queryDate.list();

                    if (dateTransferredIn.size() != 0)
                        if ((dateTransferredIn.get(0).getTime() >= newStartDate.getTime())
                                && (dateTransferredIn.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);
                        }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age 15+) who have been transferred out this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvAdultTransferredOutThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvAdultTransferredOutThisMonthList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                                + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfTransferredOut = queryDate.list();

                if (dateOfTransferredOut.size() != 0)
                    if ((dateOfTransferredOut.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfTransferredOut.get(0).getTime() <= newEndDate.getTime())) {

                        patientIdsList.add(patientId);
                    }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age <15) who have died this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsDiedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvPedsDiedThisMonthList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                    + " and ord.date_stopped is not null and ord.order_reason = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                                + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfDeath = queryDate.list();

                if (dateOfDeath.size() != 0)
                    if ((dateOfDeath.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfDeath.get(0).getTime() <= newEndDate.getTime())) {

                        patientIdsList.add(patientId);
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age <15) who have had their treatment interrupted
     * this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsFifteenInterruptTreatThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvPedsFifteenInterruptTreatThisMonthList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate
                    + "' and ord.date_stopped is not null and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2Date = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = query2Date.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDrugs = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided = 0 and ord.patient_id = " + patientId);

                    List<Integer> drugsPerPatient = queryDrugs.list();

                    SQLQuery queryDrugsDiscontinued = session.createSQLQuery("select count(*) from orders ord "
                            + " inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * " inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                            + ") and ord.voided =0 and ord.patient_id = " + patientId);

                    List<Integer> drugsDiscontinuedPerPatient = queryDrugsDiscontinued.list();

                    if (drugsPerPatient.get(0) == drugsDiscontinuedPerPatient.get(0)) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(discontinued_date as DATE) from orders ord "
                                        + "inner join drug_order do on ord.order_id = do.order_id "
                                        /*
                                         * +
                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                         */
                                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                                        + ") and (select cast(discontinued_date as DATE)) is not null and ord.voided = 0 and ord.patient_id = "
                                        + patientId);

                        List<Date> dateOfDiscontinuedDrugs = queryDate.list();

                        boolean n = true;

                        for (Date d : dateOfDiscontinuedDrugs) {

                            if ((d.getTime() >= newStartDate.getTime()) && (d.getTime() <= newEndDate.getTime())) {
                                ;
                            } else {
                                n = false;
                                break;
                            }

                        }

                        if (n == true) {
                            patientIdsList.add(patientId);
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age <15) lost to followup (>3 months)
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsLostFollowupMoreThreeMonths(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvPedsLostFollowupMoreThreeMonthsList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Session session = getSessionFactory().getCurrentSession();

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate1 = session
                            .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                    + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                    + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                    + patientId);

                    List<Date> maxEnocunterDateTime = queryDate1.list();

                    SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + endDate
                            + "' and concept_id = "
                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                            + patientId);

                    List<Date> maxReturnVisitDay = queryDate2.list();

                    if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            patientIdsList.add(patientId);
                        }
                    }

                    else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {
                            patientIdsList.add(patientId);
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of ARV patients (age <15) who have been transferred in this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsTransferredInThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvPedsTransferredInThisMonthList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetYesAsAnswerToTransferredInConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2Date = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = query2Date.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateTransferredIn = queryDate.list();

                    if (dateTransferredIn.size() != 0)
                        if ((dateTransferredIn.get(0).getTime() >= newStartDate.getTime())
                                && (dateTransferredIn.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);
                        }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of ARV patients (age <15) who have been transferred out this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#arvPedsTransferredOutThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> arvPedsTransferredOutThisMonthList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryDate = session
                        .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(obs_datetime as DATE)) <= '" + endDate + "'" + " and value_coded= "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                                + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                + patientId);

                List<Date> dateOfTransferredOut = queryDate.list();

                if (dateOfTransferredOut.size() != 0)
                    if ((dateOfTransferredOut.get(0).getTime() >= newStartDate.getTime())
                            && (dateOfTransferredOut.get(0).getTime() <= newEndDate.getTime())) {

                        patientIdsList.add(patientId);
                    }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of female adult patients (age 15 or older) who are currently
     * on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThanFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleMoreThanFifteenCurrentOnArvList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of female patients on treatment 12 months after initiation of ARVs
     * 
     * @throws ParseException
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleOnTreatTwelveAfterInitArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleOnTreatTwelveAfterInitArvList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date oneYearBeforeStartDate = df.parse(addDaysToDate(startDate, -12));

        Date oneYearBeforeEndDate = df.parse(addDaysToDate(endDate, -12));

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where pe.gender = 'F' and ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") " + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '"
                    + df.format(oneYearBeforeStartDate) + "' and (cast(ord.date_activated as DATE)) <= '"
                    + df.format(oneYearBeforeEndDate) + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.size() != 0) {

                        Date minStartDate = patientIdsMinStartDate.get(0);

                        if ((minStartDate.getTime() >= oneYearBeforeStartDate.getTime())
                                && (minStartDate.getTime() <= oneYearBeforeEndDate.getTime())) {

                            SQLQuery queryDate1 = session.createSQLQuery(
                                    "select cast(max(encounter_datetime)as DATE) from encounter where "
                                            + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                            + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                            + patientId);

                            List<Date> maxEnocunterDateTime = queryDate1.list();

                            SQLQuery queryDate2 = session
                                    .createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                            + endDate + "' and concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> maxReturnVisitDay = queryDate2.list();

                            if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                                if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                        || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate
                                                .getTime()
                                                && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                                    patientIdsList.add(patientId);

                                }
                            }

                            else if (((maxReturnVisitDay.get(0)) == null)
                                    && (maxEnocunterDateTime.get(0) != null)) {

                                if ((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime()) {

                                    patientIdsList.add(patientId);

                                }
                            } else if (((maxReturnVisitDay.get(0) != null))
                                    && (maxReturnVisitDay.get(0).getTime() > newEndDate.getTime()))

                            {
                                patientIdsList.add(patientId);

                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of female pediatric patients (age <15 years) who are
     * currently on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femalePedsUnderFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femalePedsUnderFifteenCurrentOnArvList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of male adult patients (age 15 or older) who are currently
     * on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThanFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleMoreThanFifteenCurrentOnArvList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of male patients on treatment 12 months after initiation of ARVs
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleOnTreatTwelveAfterInitArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleOnTreatTwelveAfterInitArvList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date oneYearBeforeStartDate = df.parse(addDaysToDate(startDate, -12));

        Date oneYearBeforeEndDate = df.parse(addDaysToDate(endDate, -12));

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where pe.gender = 'M' and ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") " + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '"
                    + df.format(oneYearBeforeStartDate) + "' and (cast(ord.date_activated as DATE)) <= '"
                    + df.format(oneYearBeforeEndDate) + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if (patientIdsMinStartDate.size() != 0) {

                        Date minStartDate = patientIdsMinStartDate.get(0);

                        if ((minStartDate.getTime() >= oneYearBeforeStartDate.getTime())
                                && (minStartDate.getTime() <= oneYearBeforeEndDate.getTime())) {

                            SQLQuery queryDate1 = session.createSQLQuery(
                                    "select cast(max(encounter_datetime)as DATE) from encounter where "
                                            + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                            + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                            + patientId);

                            List<Date> maxEnocunterDateTime = queryDate1.list();

                            SQLQuery queryDate2 = session
                                    .createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                            + endDate + "' and concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Date> maxReturnVisitDay = queryDate2.list();

                            if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                                if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                        || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate
                                                .getTime()
                                                && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                                    patientIdsList.add(patientId);

                                }
                            }

                            else if (((maxReturnVisitDay.get(0)) == null)
                                    && (maxEnocunterDateTime.get(0) != null)) {

                                if ((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                        && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime()) {

                                    patientIdsList.add(patientId);

                                }
                            } else if (((maxReturnVisitDay.get(0) != null))
                                    && (maxReturnVisitDay.get(0).getTime() > newEndDate.getTime()))

                            {
                                patientIdsList.add(patientId);

                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of male pediatric patients (age <15 years) who are currently
     * on ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#malePedsUnderFifteenCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> malePedsUnderFifteenCurrentOnArvList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of new adult patients who are WHO stage undefined this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultUndefinedWhoStageThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAdultUndefinedWhoStageThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetUnknownStageConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new adult patients who are WHO stage 4 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageFourThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAdultWhoStageFourThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageFourAdultConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new adult patients who are WHO stage 1 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageOneThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAdultWhoStageOneThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0  and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageOneAdultConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new adult patients who are WHO stage 3 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageThreeThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAdultWhoStageThreeThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageThreeAdultConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new adult patients who are WHO stage 2 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAdultWhoStageTwoThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAdultWhoStageTwoThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageTwoAdultConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new female adult patients (age 15+) starting ARV treatment this
     * month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleAdultStartiArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleAdultStartiArvThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pe.gender = 'F' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime())

                {
                    patientIdsList.add(patientId);
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of new female pediatric patients (age <15 years) starting ARV
     * treatment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemalePedsUnderFifteenStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemalePedsUnderFifteenStartArvThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime())

                {
                    patientIdsList.add(patientId);
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of new male adult patients (age 15+) starting ARV treatment this
     * month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleAdultStartiArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleAdultStartiArvThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 > 14 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {
                    patientIdsList.add(patientId);
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new male pediatric patients (age <15 years) starting ARV
     * treatment this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMalePedsUnderFifteenStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMalePedsUnderFifteenStartArvThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and pe.gender = 'M' and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinStartDate = session
                            .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                    + " inner join drug_order do on ord.order_id = do.order_id "
                                    /*
                                     * +
                                     * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                     */
                                    + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                    + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                    + patientId);

                    List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime())

                    {
                        patientIdsList.add(patientId);
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Number of new pediatric patients whose WHO Stage is undefined this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUndefinedWhoStageThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsUndefinedWhoStageThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {
                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetUnknownStageConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new pediatric patients (<18 months) starting ARV treatment this
     * month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderEighteenMonthStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsUnderEighteenMonthStartArvThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and ord.voided = 0 and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime())

                {
                    patientIdsList.add(patientId);
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new pediatric patients (age <5 years) starting ARV treatment
     * this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsUnderFiveStartArvThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsUnderFiveStartArvThisMonthList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {
                    patientIdsList.add(patientId);
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new pediatric patients who are WHO stage 4 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageFourThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsWhoStageFourThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageFourPedsConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new pediatric patients who are WHO Stage 1 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageOneThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsWhoStageOneThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(max(obs_datetime) as DATE))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageOnePedsConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new pediatric patients who are WHO Stage 3 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageThreeThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsWhoStageThreeThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageThreePedsConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }

            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Number of new pediatric patients who are WHO Stage 2 this month
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newPedsWhoStageTwoThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newPedsWhoStageTwoThisMonthList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                    + "and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                    + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId()) + " and pg.program_id= "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                    + endDate + "' ");

            List<Integer> patientIds1 = query1.list();
            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " inner join drug_order do on ord.order_id = do.order_id "
                                /*
                                 * +
                                 * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                 */
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if ((patientIds2.size() == 0) && (patientIdsMinStartDate.size() != 0))

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && (patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()))

                    {

                        SQLQuery queryDate = session.createSQLQuery(
                                "select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                        + " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfWhoStage = queryDate.list();

                        if (dateOfWhoStage.size() != 0) {
                            SQLQuery valueCoded = session
                                    .createSQLQuery("select value_coded from obs where concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetWhoStageConceptId())
                                            + " and (select(cast(obs_datetime as Date))) = " + "'"
                                            + dateOfWhoStage.get(0) + " ' "
                                            + " and value_coded is not null and voided = 0 and person_id = "
                                            + patientId);

                            List<Integer> PatientValueCoded = valueCoded.list();

                            if (PatientValueCoded.size() != 0)
                                if (PatientValueCoded.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetWhoStageTwoPedsConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                        }
                    }

            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * Total number of pediatric patients who are on First Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsOnFirstLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pedsOnFirstLineRegList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfFirstLineDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfSecondLineDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of pediatric patients who are on Second Line Regimen
     * 
     * @throws ParseException
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsOnSecondLineReg(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pedsOnSecondLineRegList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + "  and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfSecondLineDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.program_id= " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId())
                    + " and pg.date_enrolled <= '" + endDate + "' ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of pediatric patients (age <18 months) who are currently on
     * ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderEighteenMonthsCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pedsUnderEighteenMonthsCurrentOnArvList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 2 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * Total number of pediatric patients (age <5 years) who are currently on
     * ARV treatment
     * 
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveCurrentOnArv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pedsUnderFiveCurrentOnArvList(String startDate, String endDate) throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 4 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                patientIdsList.add(patientId);

            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    // ------------C. STIs, Opportunistic Infections and Others-------------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#clientsCounceledForStiThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> clientsCounceledForStiThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#opportInfectTreatedExcludeTbThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> opportInfectTreatedExcludeTbThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryOpportunisticInfectionTB = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                                    + " and o.value_coded = "
                                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionTBConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIdsqueryOpportunisticInfectionTB = queryOpportunisticInfectionTB.list();

                    if (patientIdsqueryOpportunisticInfectionTB.size() == 0) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                                        + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateOfOpportunisticInfections = queryDate.list();

                        if (dateOfOpportunisticInfections.size() != 0)
                            if ((dateOfOpportunisticInfections.get(0).getTime() >= newStartDate.getTime())
                                    && (dateOfOpportunisticInfections.get(0).getTime() <= newEndDate.getTime())) {

                                patientIdsList.add(patientId);
                            }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#stiDiagnosedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> stiDiagnosedThisMonthList(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
                    + endDate + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 14 "
                    + " and pg.voided = 0 and pe.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and pg.date_enrolled >= '" + startDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionsConceptId())
                    + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetOpportunisticInfectionSTIConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(
                                            GlobalProperties.gpGetEndDateOfOpportunisticInfectionSTIConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfEndDateOfSTI = queryDate.list();

                    if (dateOfEndDateOfSTI.size() != 0)
                        if ((dateOfEndDateOfSTI.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfEndDateOfSTI.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);
                        }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;

    }

    // ----------D. Nutrition Consultation Data Elements------------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultSevereMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> adultSevereMalnutrTherapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    public List<Person> numberOfPatientsWhoReceivedFollowUpAndAdherenceCounsellingList(String startDate,
            String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    public List<Person> numberOfPatientsWhoReceivedFamilyPlanningThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#adultTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> adultTherapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#lactatingMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> lactatingMalnutrTherapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pedsTherapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFifteenSevMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pedsUnderFifteenSevMalnutrTherapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveSevereMalnutrTheurapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pedsUnderFiveSevereMalnutrTheurapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveSevereMalnutrThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pedsUnderFiveSevereMalnutrThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        // List<Integer> patientIdsList = new ArrayList<Integer>();
        //
        ArrayList<Person> patients = new ArrayList<Person>();
        //
        // SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        //
        // Date newEndDate = df.parse(endDate);
        //
        // Date newStartDate = df.parse(startDate);
        //
        // Session session = getSessionFactory().getCurrentSession();
        //
        // double weight;
        //
        // double height;
        //
        // double resultWeightHeight;
        //
        // double resultWeightAge;
        //
        // double age;
        //
        // SQLQuery query1 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('"
        // + endDate
        // + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 5 "
        // + " and pg.program_id= "
        // + Integer
        // .parseInt(GlobalProperties.gpGetHIVProgramId())
        // + " and pg.date_enrolled <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and pg.date_completed is null ");
        //
        // List<Integer> patientIds1 = query1.list();
        //
        // for (Integer patientId : patientIds1) {
        //
        // weight = 0;
        //
        // height = 0;
        //
        // resultWeightHeight = 0;
        //
        // resultWeightAge = 0;
        //
        // age = 0;
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and (cast(o.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and o.voided = 0 and o.person_id="
        // + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0)
        //
        // {
        //
        // SQLQuery queryDateWeight = session
        // .createSQLQuery("select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetWeightConceptId())
        // +
        // " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Date> dateOfWeight = queryDateWeight.list();
        //
        // if (dateOfWeight.size() != 0) {
        // SQLQuery valueNumericOfWeight = session
        // .createSQLQuery("select value_numeric from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetWeightConceptId())
        // + " and (select(cast(obs_datetime as Date))) = "
        // + "'"
        // + dateOfWeight.get(0)
        // + " ' "
        // + " and value_numeric is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Double> PatientValueNumericOfWeight = valueNumericOfWeight
        // .list();
        //
        // if (PatientValueNumericOfWeight.size() != 0) {
        //
        // weight = PatientValueNumericOfWeight.get(0);
        // }
        //
        // }
        //
        // SQLQuery queryDateHeight = session
        // .createSQLQuery("select (cast(max(obs_datetime) as DATE)) from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetHeightConceptId())
        // +
        // " and (select (cast(max(obs_datetime) as DATE))) is not null and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Date> dateOfHeight = queryDateHeight.list();
        //
        // if (dateOfHeight.size() != 0) {
        // SQLQuery valueNumericOfHeight = session
        // .createSQLQuery("select value_numeric from obs where concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetHeightConceptId())
        // + " and (select(cast(obs_datetime as Date))) = "
        // + "'"
        // + dateOfHeight.get(0)
        // + " ' "
        // + " and value_numeric and voided = 0 and person_id = "
        // + patientId);
        //
        // List<Double> PatientValueNumericOfHeight = valueNumericOfHeight
        // .list();
        //
        // if (PatientValueNumericOfHeight.size() != 0) {
        //
        // height = PatientValueNumericOfHeight.get(0);
        // }
        // }
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded IN ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        //
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // +
        // "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate.list();
        //
        // if (HivTestResultDate.size() != 0)
        //
        // {
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetResultForHIVTestConceptId())
        // + " and o.value_coded in ("
        // + GlobalProperties
        // .gpGetListOfAnswersToResultOfHIVTest()
        // + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // +
        // "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
        // + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == Integer
        // .parseInt(GlobalProperties
        // .gpGetPositiveAsResultToHIVTestConceptId())) {
        //
        // SQLQuery queryAge = session
        // .createSQLQuery("select DATE_FORMAT(FROM_DAYS(TO_DAYS('2010-01-01') - TO_DAYS(pe.birthdate)), '%Y')+0 < 5 "
        // + " from person pe where pe.voided = 0 and pe.person_id="
        // + patientId);
        //
        // List<Double> patientIdsAge = queryAge.list();
        //
        // if (patientIdsAge.size() != 0) {
        //
        // age = patientIdsAge.get(0);
        // }
        //
        // resultWeightHeight = weight / height;
        //
        // resultWeightAge = weight / age;
        //
        // if ((resultWeightHeight < -3)
        // || (resultWeightAge < -3)) {
        //
        // patientIdsList.add(patientId);
        // }
        // }
        // }
        // }
        // }
        // }
        // }
        //
        // for (Integer patientId : patientIdsList) {
        // patients.add(Context.getPersonService().getPerson(patientId));
        // }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pedsUnderFiveWithSevMalnutrThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pedsUnderFiveWithSevMalnutrThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantMalnutrTherapThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pregnantMalnutrTherapThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    // ----------A. Antenatal Data Elements-----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#discordantCouples1(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> discordantCouples1List(String startDate, String endDate) {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()) + " ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded IN ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {

                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded IN ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultDatePartner = session.createSQLQuery(
                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                            + Integer.parseInt(
                                                    GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                            + " and o.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                            + patientId);
                            List<Date> HivTestResultDatePartner = queryHIVResultDatePartner.list();

                            if (HivTestResultDatePartner.size() != 0) {

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);

                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    SQLQuery queryHIVResultConceptPartner = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and o.value_coded IN ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDatePartner.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConceptPartner = queryHIVResultConceptPartner.list();

                                    if (HivTestResultConceptPartner.size() != 0) {

                                        if (((HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId()))
                                                && (HivTestResultConceptPartner.get(0) == Integer
                                                        .parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())))
                                                || ((HivTestResultConcept.get(0) == Integer.parseInt(
                                                        GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()))
                                                        && (HivTestResultConceptPartner.get(0) == Integer
                                                                .parseInt(GlobalProperties
                                                                        .gpGetNegativeAsResultToHIVTestConceptId())))) {

                                            patientIdsList.add(patientId);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#hivNegPregnantPartnersTestedHivPos(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> hivNegPregnantPartnersTestedHivPosList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()) + " ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id= " + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded IN ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {

                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded IN ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultDatePartner = session.createSQLQuery(
                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                            + Integer.parseInt(
                                                    GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                            + " and o.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                            + patientId);
                            List<Date> HivTestResultDatePartner = queryHIVResultDatePartner.list();

                            if (HivTestResultDatePartner.size() != 0) {

                                if ((HivTestResultDatePartner.get(0).getTime() >= newStartDate.getTime())
                                        && (HivTestResultDatePartner.get(0).getTime() <= newEndDate.getTime())) {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded IN ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);

                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        SQLQuery queryHIVResultConceptPartner = session.createSQLQuery(
                                                "select o.value_coded from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded IN ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                        + HivTestResultDatePartner.get(0)
                                                        + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                        + patientId);
                                        List<Integer> HivTestResultConceptPartner = queryHIVResultConceptPartner
                                                .list();

                                        if (HivTestResultConceptPartner.size() != 0) {

                                            if ((HivTestResultConcept.get(0) == Integer.parseInt(
                                                    GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId()))
                                                    && (HivTestResultConceptPartner.get(0) == Integer
                                                            .parseInt(GlobalProperties
                                                                    .gpGetPositiveAsResultToHIVTestConceptId()))) {

                                                patientIdsList.add(patientId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#negativeWomenReturnRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> negativeWomenReturnResList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVResultReceivedDate = session.createSQLQuery(
                            "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                                    + " and (select cast(min(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                    + patientId);
                    List<Date> HivTestResultReceivedDate = queryHIVResultReceivedDate.list();

                    if (HivTestResultReceivedDate.size() != 0) {

                        if ((HivTestResultReceivedDate.get(0).getTime() >= newStartDate.getTime())
                                && (HivTestResultReceivedDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session.createSQLQuery("select distinct pe.person_id from person pe "
                                    + "inner join obs ob on pe.person_id = ob.person_id " + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and ob.voided = 0 and pe.person_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {
                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(min(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(min(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                            patientIdsList.add(patientId);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#partnersTestedHivPos(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> partnersTestedHivPosList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "inner join encounter enc on pg.patient_id = enc.patient_id "
        // + "where pe.gender = 'f' and ob.concept_id = "
        // + ConstantValues.TESTING_STATUS_OF_PARTNER_ID
        // + " and (cast(ob.obs_datetime as DATE)) >= '"
        // + startDate
        // + "' AND (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
        // + " and pg.date_completed is null ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + ConstantValues.REASON_FOR_EXITING_CARE
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + "and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate
        // .list();
        //
        // SQLQuery queryHIVResultDatePartner = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + ConstantValues.TESTING_STATUS_OF_PARTNER_ID
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDatePartner = queryHIVResultDatePartner
        // .list();
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + "and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // SQLQuery queryHIVResultConceptPartner = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + ConstantValues.TESTING_STATUS_OF_PARTNER_ID
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDatePartner.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConceptPartner =
        // queryHIVResultConceptPartner
        // .list();
        //
        // if ((HivTestResultConcept.size() != 0)
        // && (HivTestResultConceptPartner.size() != 0)) {
        //
        // if ((HivTestResultConcept.get(0) == ConstantValues.POSITIVE_ID)
        // && (HivTestResultConceptPartner.get(0) ==
        // ConstantValues.POSITIVE_ID)) {
        //
        // Person patient = Context.getPersonService()
        // .getPerson(patientId);
        // patients.add(patient);
        // }
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPos(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pregnantHivPosList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0)

                        {

                            if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                    && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);
                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    if (HivTestResultConcept.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                        patientIdsList.add(patientId);
                                    }

                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosAztProphyAt28Weeks(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pregnantHivPosAztProphyAt28WeeksList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosEligibleArvs1(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pregnantHivPosEligibleArvs1List(String startDate, String endDate) {

        double val = 0;

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id " + "where o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                    + " and pe.gender = 'f' and (cast(o.obs_datetime as DATE)) <= '" + endDate
                    + "' and pg.program_id= " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and o.voided = 0 ");

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query2Date = session
                            .createSQLQuery("select cast(max(obs_datetime) as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                                    + " and (select cast(max(obs_datetime) as DATE)) <= '" + endDate
                                    + "' and (select cast(max(obs_datetime) as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> maxObsDateTimeCD4Count = query2Date.list();

                    if (maxObsDateTimeCD4Count.size() != 0) {

                        SQLQuery query3 = session.createSQLQuery("select value_numeric from obs where concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                                + " and obs_datetime = '" + maxObsDateTimeCD4Count.get(0)
                                + "' and value_numeric is not null and voided = 0 and person_id = " + patientId);

                        List<Double> maxValueNumericCD4Count = query3.list();

                        // Double val = (maxValueNumericCD4Count.get(0) > 0) ?
                        // maxValueNumericCD4Count
                        // .get(0)
                        // : 400;

                        if (maxValueNumericCD4Count.size() != 0)

                        {

                            // val = maxValueNumericCD4Count.get(0);

                            if (maxValueNumericCD4Count.get(0) < 350.0) {

                                SQLQuery query4 = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "inner join obs o on pe.person_id = o.person_id "
                                                + "inner join orders ord on pg.patient_id = ord.patient_id "
                                                + "inner join drug_order do on ord.order_id = do.order_id "
                                                /*
                                                 * +
                                                 * "inner join drug d on do.drug_inventory_id = d.drug_id "
                                                 */
                                                + "where ord.concept_id IN ("
                                                + GlobalProperties.gpGetListOfARVsDrugs()
                                                + ") and (cast(ord.date_activated as DATE)) <= '" + endDate
                                                + "' and pg.program_id= "
                                                + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                + " and pg.voided = 0 and pe.voided = 0 and pa.voided = 0 and o.voided = 0 and ord.voided = 0 and pg.patient_id =  "
                                                + patientId);

                                List<Integer> patientIds4 = query4.list();

                                if (patientIds4.size() == 0) {

                                    patientIdsList.add(patientId);

                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosEligibleArvs2(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pregnantHivPosEligibleArvs2List(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0)

                        {

                            if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                    && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);
                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    if (HivTestResultConcept.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                        SQLQuery queryMinStartDate = session.createSQLQuery(
                                                "select (cast(min(ord.date_activated)as Date)) from orders ord "
                                                        + " inner join drug_order do on ord.order_id = do.order_id "
                                                        /*
                                                         * +
                                                         * " inner join drug d on do.drug_inventory_id = d.drug_id "
                                                         */
                                                        + " where ord.concept_id IN ("
                                                        + GlobalProperties.gpGetListOfARVsDrugs() + ") "
                                                        + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                                        + patientId);

                                        List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                                        if (patientIdsMinStartDate.size() != 0) {
                                            if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                                    && patientIdsMinStartDate.get(0).getTime() <= newEndDate
                                                            .getTime()) {

                                                patientIdsList.add(patientId);
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return patients;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosTripleTheraProphy(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pregnantHivPosTripleTheraProphyList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantPartnersTestedForHiv(java.lang.String,
     *      java.lang.String)
     */
    // @SuppressWarnings("unchecked")
    @Override
    public List<Person> pregnantPartnersTestedForHivList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();
        //
        // List<Integer> patientIdsList = new ArrayList<Integer>();
        //
        // SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        //
        // Date newEndDate = df.parse(endDate);
        //
        // Date newStartDate = df.parse(startDate);
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "inner join encounter enc on pg.patient_id = enc.patient_id "
        // + "where pe.gender = 'f' and ob.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and (cast(ob.obs_datetime as DATE)) >= '"
        // + startDate
        // + "' AND (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
        // + " and pg.program_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetPMTCTProgramId())
        // + " and pg.date_completed is null ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + Integer.parseInt(GlobalProperties
        // .gpGetExitFromCareConceptId())
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery queryPartnerHIVTest = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + Integer
        // .parseInt(GlobalProperties
        // .gpGetTestingStatusOfPartnerConceptId())
        // + " and o.person_id= " + patientId);
        //
        // List<Date> partnerHIVTestDate = queryPartnerHIVTest.list();
        //
        // if (partnerHIVTestDate.size() != 0) {
        //
        // if ((partnerHIVTestDate.get(0).getTime() >= newStartDate
        // .getTime())
        // && (partnerHIVTestDate.get(0).getTime() <= newEndDate
        // .getTime())) {
        //
        // patientIdsList.add(patientId);
        // }
        // }
        // }
        // }
        //
        // for (Integer patientId : patientIdsList) {
        // patients.add(Context.getPersonService().getPerson(patientId));
        // }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantTestedPosForRpr(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pregnantTestedPosForRprList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryCD4CountTest = session.createSQLQuery(
                            "select cast(max(o.obs_datetime) as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                                    + " and o.value_coded IN ("
                                    + GlobalProperties.gpGetListOfAnswersToRapidPlasminReagent()
                                    + ") and (select cast(max(o.obs_datetime) as DATE)) is not null and o.voided= 0 and o.person_id= "
                                    + patientId);
                    List<Date> rprTestDate = queryCD4CountTest.list();

                    if (rprTestDate.size() != 0) {

                        if ((rprTestDate.get(0).getTime() >= newStartDate.getTime())
                                && (rprTestDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery queryHIVResult = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                                            + " and o.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToRapidPlasminReagent()
                                            + ") and o.obs_datetime = '" + rprTestDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id="
                                            + patientId);

                            List<Integer> rprTestResult = queryHIVResult.list();

                            if (rprTestResult.size() != 0) {

                                if (rprTestResult.get(0) == Integer.parseInt(GlobalProperties
                                        .gpGetreactiveAsfAnswerToRapidPlasminReagentConceptIdConceptId())) {

                                    patientIdsList.add(patientId);
                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosReturnRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosReturnResList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVResultReceivedDate = session.createSQLQuery(
                            "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetDateResultOfHIVTestReceivedConceptId())
                                    + " and (select cast(min(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                    + patientId);
                    List<Date> HivTestResultReceivedDate = queryHIVResultReceivedDate.list();

                    if (HivTestResultReceivedDate.size() != 0) {

                        if ((HivTestResultReceivedDate.get(0).getTime() >= newStartDate.getTime())
                                && (HivTestResultReceivedDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session.createSQLQuery("select distinct pe.person_id from person pe "
                                    + "inner join obs ob on pe.person_id = ob.person_id " + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and ob.voided = 0 and pe.person_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {
                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(min(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(min(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            patientIdsList.add(patientId);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosTestedCd4(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosTestedCd4List(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
                    + " and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryCD4CountTest = session.createSQLQuery(
                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetCD4CountConceptId())
                                    + " and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Date> cd4CountTestDate = queryCD4CountTest.list();

                    if (cd4CountTestDate.size() != 0) {

                        if ((cd4CountTestDate.get(0).getTime() >= newStartDate.getTime())
                                && (cd4CountTestDate.get(0).getTime() <= newEndDate.getTime())) {
                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            patientIdsList.add(patientId);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenKnownHivPosFirstAntenatal(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenKnownHivPosFirstAntenatalList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                    + " and pe.gender= 'f' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinCPNEncounter = session.createSQLQuery(
                            "select cast(min(encounter_datetime)as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                                    + " and (select cast(min(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id ="
                                    + patientId);

                    List<Date> minCPNEncounter = queryMinCPNEncounter.list();

                    if (minCPNEncounter.size() != 0) {

                        if ((minCPNEncounter.get(0).getTime() >= newStartDate.getTime())
                                && (minCPNEncounter.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() != 0) {
                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                SQLQuery queryHIVResultConcept = session
                                        .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                + HivTestResultDate.get(0)
                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                + patientId);
                                List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                if (HivTestResultConcept.size() != 0) {

                                    if (HivTestResultConcept.get(0) == Integer
                                            .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                        patientIdsList.add(patientId);

                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenTestedForRpr(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenTestedForRprList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                    + "where pe.gender = 'f' and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryRPRTest = session.createSQLQuery(
                            "select cast(max(o.obs_datetime) as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetRapidPlasminReagentConceptId())
                                    + " and (select cast(max(o.obs_datetime) as DATE)) is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Date> rprTestDate = queryRPRTest.list();

                    if (rprTestDate.size() != 0) {

                        if ((rprTestDate.get(0).getTime() >= newStartDate.getTime())
                                && (rprTestDate.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivFirstAntenatal(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenUnknownHivFirstAntenatalList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient pa on pe.person_id = pa.patient_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id "
                    + "inner join encounter enc on pe.person_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                    + " AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and pe.gender ='f' and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMinCPNEncounter = session.createSQLQuery(
                            "select cast(min(encounter_datetime)as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId())
                                    + " and (select cast(min(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id ="
                                    + patientId);

                    List<Date> minCPNEncounter = queryMinCPNEncounter.list();

                    if (minCPNEncounter.size() != 0) {

                        if ((minCPNEncounter.get(0).getTime() >= newStartDate.getTime())
                                && (minCPNEncounter.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session.createSQLQuery("select distinct pe.person_id from person pe "
                                    + "inner join obs ob on pe.person_id = ob.person_id "
                                    + "inner join patient pa on pe.person_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and pe.voided = 0 and ob.voided = 0 and pa.voided = 0 and pe.person_id = "
                                    + patientId);

                            List<Integer> patientIds3 = query3.list();

                            if (patientIds3.size() == 0) {

                                patientIdsList.add(patientId);
                            }

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenUnknownHivTestedList(String startDate, String endDate) throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient_program pg on pe.person_id = pg.patient_id " + "where ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                    + " AND (cast(ob.obs_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.obs_datetime as DATE)) <= '" + endDate + "' and pg.program_id = "
                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                    + " and pe.gender ='f' and ob.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVResultDate = session.createSQLQuery(
                            "select cast(min(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (select cast(min(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                    + patientId);

                    List<Date> HivTestResultDate = queryHIVResultDate.list();

                    if (HivTestResultDate.size() != 0) {

                        if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);
                        }

                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    // ---------B. Maternity Data Elements--------

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#expectedDeliveriesAmongHivPosWomen(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> expectedDeliveriesAmongHivPosWomenList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                    + " and (cast(ob.value_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.value_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
                    + " and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMaternity = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                                    + "where enc.encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and pg.voided = 0 and enc.voided = 0 and pg.patient_id = " + patientId);

                    // Getting the size of the returned LIST which equals to the
                    // COUNTS
                    // needed
                    List<Integer> patientIds3 = queryMaternity.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                                "select cast(max(o.value_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(
                                                GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                                        + " and (select cast(max(o.value_datetime)as DATE)) is not null and o.voided = 0 and o.person_id= "
                                        + patientId);
                        List<Date> estimateDateOfDelivery = queryEstimatedDateOfDelivery.list();

                        if (estimateDateOfDelivery.size() != 0) {

                            if ((estimateDateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                    && (estimateDateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                                SQLQuery query3 = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "where ob.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                + " and pg.patient_id = " + patientId);

                                List<Integer> patientIds4 = query3.list();

                                if (patientIds4.size() != 0) {

                                    SQLQuery queryHIVResultDate = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDate = queryHIVResultDate.list();

                                    if (HivTestResultDate.size() != 0)

                                    {

                                        SQLQuery queryHIVResultConcept = session.createSQLQuery(
                                                "select o.value_coded from obs o where o.concept_id = "
                                                        + Integer.parseInt(
                                                                GlobalProperties.gpGetResultForHIVTestConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                        + HivTestResultDate.get(0)
                                                        + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                        + patientId);
                                        List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                        if (HivTestResultConcept.size() != 0) {

                                            if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                    GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                                patientIdsList.add(patientId);
                                            }
                                        }

                                    }

                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#expectedDeliveriesFacilityThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> expectedDeliveriesFacilityThisMonthList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetCPNEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                    + " and (cast(ob.value_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(ob.value_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 "
                    + " and pg.program_id = " + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId()));

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryMaternity = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join encounter enc on pg.patient_id = enc.patient_id "
                                    + "where enc.encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and pg.voided = 0 and enc.voided = 0 and pg.patient_id = " + patientId);

                    // Getting the size of the returned LIST which equals to the
                    // COUNTS
                    // needed
                    List<Integer> patientIds3 = queryMaternity.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                                "select cast(max(o.value_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(
                                                GlobalProperties.gpGetEstimatedDateOfConfinementConceptId())
                                        + " and (select cast(max(o.value_datetime)as DATE)) is not null and o.voided = 0 and o.person_id= "
                                        + patientId);
                        List<Date> estimateDateOfDelivery = queryEstimatedDateOfDelivery.list();

                        if (estimateDateOfDelivery.size() != 0) {

                            if ((estimateDateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                    && (estimateDateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                                patientIdsList.add(patientId);
                            }
                        }

                    }

                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#occuringDeliveriesFacilityThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> occuringDeliveriesFacilityThisMonthList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select cast(encounter_datetime as DATE)) is not null and voided =  0 and patient_id= "
                                    + patientId);

                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {
                            patientIdsList.add(patientId);
                        }

                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantReceivedCompleteCourseThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> pregnantReceivedCompleteCourseThisMonthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#reportedHivPosGivingBirthAtHome(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> reportedHivPosGivingBirthAtHomeList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosAzt3tcNvpDuringLabor(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> womenHivPosAzt3tcNvpDuringLaborList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosGivingBirthAtFacility(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosGivingBirthAtFacilityList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);
        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided=0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select cast(encounter_datetime as DATE)) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds4 = query3.list();

                            if (patientIds4.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            patientIdsList.add(patientId);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenReceivingAzt3tcAfterDelivery(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> womenReceivingAzt3tcAfterDeliveryList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivStatusTestedDuringLabor1(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenUnknownHivStatusTestedDuringLabor1List(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient pa on pe.person_id = pa.patient_id " + "where ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and ob.value_numeric = 1 ");

            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVTestInDeliveryRoom = session.createSQLQuery(
                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                                    + " and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.value_numeric = 1 and o.person_id= "
                                    + patientId);
                    List<Date> testInDeliveryRoomDate = queryHIVTestInDeliveryRoom.list();

                    if (testInDeliveryRoomDate.size() != 0) {

                        if ((testInDeliveryRoomDate.get(0).getTime() >= newStartDate.getTime())
                                && (testInDeliveryRoomDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery queryHIVTest = session
                                    .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.obs_datetime < '" + testInDeliveryRoomDate.get(0)
                                            + "' and o.voided = 0 and o.person_id=" + patientId);

                            List<Integer> patientIds3 = queryHIVTest.list();

                            if (patientIds3.size() == 0) {

                                patientIdsList.add(patientId);
                            }
                        }
                    }
                }
            }
            // } catch (Exception e) {
            // // TODO: handle exception
            // }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenUnknownHivStatusTestedPosDuringLabor2(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenUnknownHivStatusTestedPosDuringLabor2List(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery query = session.createSQLQuery("select distinct pe.person_id from person pe "
                    + "inner join obs ob on pe.person_id = ob.person_id "
                    + "inner join patient pa on pe.person_id = pa.patient_id " + "where ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                    + " and (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                    + "' and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and ob.value_numeric = 1 ");

            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryHIVTestInDeliveryRoom = session.createSQLQuery(
                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetHIVTestInDeliveryRoomConceptId())
                                    + " and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.value_numeric = 1 and o.person_id= "
                                    + patientId);
                    List<Date> testInDeliveryRoomDate = queryHIVTestInDeliveryRoom.list();

                    if (testInDeliveryRoomDate.size() != 0) {

                        if ((testInDeliveryRoomDate.get(0).getTime() >= newStartDate.getTime())
                                && (testInDeliveryRoomDate.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery queryHIVTest = session
                                    .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.obs_datetime < '" + testInDeliveryRoomDate.get(0)
                                            + "' and o.voided = 0 and o.person_id=" + patientId);

                            List<Integer> patientIds3 = queryHIVTest.list();

                            if (patientIds3.size() == 0) {

                                SQLQuery query4 = session
                                        .createSQLQuery("select distinct pe.person_id from person pe "
                                                + "inner join obs ob on pe.person_id = ob.person_id "
                                                + "where ob.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded IN ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and pe.voided = 0 and ob.voided = 0 and pe.person_id = "
                                                + patientId);

                                List<Integer> patientIds4 = query4.list();

                                if (patientIds4.size() != 0) {

                                    SQLQuery queryHIVResultDate = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDate = queryHIVResultDate.list();

                                    if (HivTestResultDate.size() != 0)

                                    {

                                        if ((HivTestResultDate.get(0).getTime() >= newStartDate.getTime())
                                                && (HivTestResultDate.get(0).getTime() <= newEndDate.getTime())) {

                                            SQLQuery queryHIVResultConcept = session.createSQLQuery(
                                                    "select o.value_coded from obs o where o.concept_id = "
                                                            + Integer.parseInt(GlobalProperties
                                                                    .gpGetResultForHIVTestConceptId())
                                                            + " and o.value_coded in ("
                                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                            + HivTestResultDate.get(0)
                                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                            + patientId);
                                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                            if (HivTestResultConcept.size() != 0) {

                                                if (HivTestResultConcept.get(0) == Integer.parseInt(GlobalProperties
                                                        .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    patientIdsList.add(patientId);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    // -----------C. HIV Exposed Infant Follow-up------------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersAged6WeeksThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> infantHivPosMothersAged6WeeksThisMonthList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct rel.person_a from relationship rel "
        // + "inner join person pe on rel.person_a = pe.person_id "
        // + "where pe.gender = 'f' "
        // + " and rel.voided = 0 and pe.voided = 0 ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + ConstantValues.REASON_FOR_EXITING_CARE
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate
        // .list();
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == ConstantValues.POSITIVE_ID) {
        //
        // SQLQuery infantHIVPositiveInPMTCT = session
        // .createSQLQuery("select distinct rel.person_b from relationship rel "
        // + "inner join person pe on rel.person_b = pe.person_id "
        // + "inner join encounter en on rel.person_b = en.patient_id "
        // + "inner join patient_program pg on rel.person_b = pg.patient_id "
        // + "where rel.person_a = "
        // + patientId
        // + " and pe.birthdate >= '"
        // + startDate
        // + "' and pe.birthdate <= '"
        // + startDate
        // + "' and SELECT DATEDIFF(('"
        // + endDate
        // + "'),pe.birthdate)/30 < 2 ");
        // List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
        // .list();
        //
        // if (infantHIVPositive.size() != 0) {
        //
        // Person patient = Context.getPersonService()
        // .getPerson(patientId);
        // patients.add(patient);
        // }
        // }
        //
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersAged9MonthsThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> infantHivPosMothersAged9MonthsThisMonthList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct rel.person_a from relationship rel "
        // + "inner join person pe on rel.person_a = pe.person_id "
        // + "where pe.gender = 'f' "
        // + " and rel.voided = 0 and pe.voided = 0 ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + ConstantValues.REASON_FOR_EXITING_CARE
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate
        // .list();
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == ConstantValues.POSITIVE_ID) {
        //
        // SQLQuery infantHIVPositiveInPMTCT = session
        // .createSQLQuery("select distinct rel.person_b from relationship rel "
        // + "inner join person pe on rel.person_b = pe.person_id "
        // + "inner join encounter en on rel.person_b = en.patient_id "
        // + "inner join patient_program pg on rel.person_b = pg.patient_id "
        // + "where rel.person_a = "
        // + patientId
        // + " and pe.birthdate >= '"
        // + startDate
        // + "' and pe.birthdate <= '"
        // + startDate
        // + "' and SELECT DATEDIFF(('"
        // + endDate
        // + "'),pe.birthdate)/30 = 9 ");
        // List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
        // .list();
        //
        // if (infantHIVPositive.size() != 0) {
        //
        // Person patient = Context.getPersonService()
        // .getPerson(patientId);
        // patients.add(patient);
        // }
        // }
        //
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersAgedAt18MonthsThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> infantHivPosMothersAgedAt18MonthsThisMonthList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        // try {
        //
        // Session session = getSessionFactory().getCurrentSession();
        // SQLQuery query = session
        // .createSQLQuery("select distinct rel.person_a from relationship rel "
        // + "inner join person pe on rel.person_a = pe.person_id "
        // + "where pe.gender = 'f' "
        // + " and rel.voided = 0 and pe.voided = 0 ");
        //
        // // Getting the size of the returned LIST which equals to the COUNTS
        // // needed
        // List<Integer> patientIds = query.list();
        //
        // for (Integer patientId : patientIds) {
        //
        // SQLQuery query2 = session
        // .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
        // + ConstantValues.REASON_FOR_EXITING_CARE
        // + " and o.person_id=" + patientId);
        //
        // List<Integer> patientIds2 = query2.list();
        //
        // if (patientIds2.size() == 0) {
        //
        // SQLQuery query3 = session
        // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
        // + "inner join obs ob on pg.patient_id = ob.person_id "
        // + "inner join person pe on pg.patient_id = pe.person_id "
        // + "inner join patient pa on pg.patient_id = pa.patient_id "
        // + "where ob.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and (cast(ob.obs_datetime as DATE)) <= '"
        // + endDate
        // + "' and ob.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (cast(pg.date_enrolled as DATE)) <= '"
        // + endDate
        // +
        // "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
        // + "and pg.date_completed is null and pg.patient_id = "
        // + patientId);
        //
        // List<Integer> patientIds3 = query3.list();
        //
        // if (patientIds3.size() != 0) {
        // SQLQuery queryHIVResultDate = session
        // .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
        // + endDate
        // + "' and o.person_id="
        // + patientId);
        // List<Date> HivTestResultDate = queryHIVResultDate
        // .list();
        //
        // SQLQuery queryHIVResultConcept = session
        // .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
        // + ConstantValues.RESULT_OF_HIV_TEST
        // + " and o.value_coded in "
        // + ConstantValues.LIST_OF_ANSWERS_TO_RESULT_OF_HIV_TEST
        // + " and (select cast(max(o.obs_datetime)as DATE)) = '"
        // + HivTestResultDate.get(0)
        // + "' and o.person_id= " + patientId);
        // List<Integer> HivTestResultConcept = queryHIVResultConcept
        // .list();
        //
        // if (HivTestResultConcept.size() != 0) {
        //
        // if (HivTestResultConcept.get(0) == ConstantValues.POSITIVE_ID) {
        //
        // SQLQuery infantHIVPositiveInPMTCT = session
        // .createSQLQuery("select distinct rel.person_b from relationship rel "
        // + "inner join person pe on rel.person_b = pe.person_id "
        // + "inner join encounter en on rel.person_b = en.patient_id "
        // + "inner join patient_program pg on rel.person_b = pg.patient_id "
        // + "where rel.person_a = "
        // + patientId
        // + " and pe.birthdate >= '"
        // + startDate
        // + "' and pe.birthdate <= '"
        // + startDate
        // + "' and SELECT DATEDIFF(('"
        // + endDate
        // + "'),pe.birthdate)/30 = 18 ");
        // List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
        // .list();
        //
        // if (infantHIVPositive.size() != 0) {
        //
        // Person patient = Context.getPersonService()
        // .getPerson(patientId);
        // patients.add(patient);
        // }
        // }
        //
        // }
        // }
        // }
        // }
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersCotrimoAt6Weeks(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> infantHivPosMothersCotrimoAt6WeeksList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersEnrolledPmtct(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersEnrolledPmtctList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + "inner join person pe on rel.person_b = pe.person_id "
                                                    + "inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + "where rel.person_a = " + patientId + " and pg.program_id = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())

                                                    + " and pg.voided = 0 and rel.voided = 0 and pe.voided = 0 and (cast(pg.date_enrolled as DATE)) >= '"
                                                    + startDate + "' and (cast(pg.date_enrolled as DATE)) <= '"
                                                    + endDate + "' ");
                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() != 0) {

                                                SQLQuery queryExposedInfantInPMTCT = session.createSQLQuery(
                                                        "select (cast(pg.date_enrolled as DATE)) from patient_program pg"
                                                                + " where pg.patient_id = " + patientIdsInfant
                                                                + " and (select (cast(pg.date_enrolled as DATE))) is not null and pg.voided = 0 and pg.program_id = "
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId()));

                                                List<Date> exposedInfantInPMTCT = queryExposedInfantInPMTCT.list();

                                                if ((exposedInfantInPMTCT.get(0).getTime() >= newStartDate
                                                        .getTime())
                                                        && (exposedInfantInPMTCT.get(0).getTime() <= newEndDate
                                                                .getTime())) {

                                                    patientIdsList.add(infantHIVPositive.get(0));
                                                }
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersLostFollowup(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersLostFollowupList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        List<Integer> patientIdsList = new ArrayList<Integer>();

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select (cast(pg.date_enrolled as DATE))) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryDate1 = session.createSQLQuery(
                                                        "select cast(max(encounter_datetime)as DATE) from encounter where "
                                                                + "(select(cast(max(encounter_datetime)as Date))) <= '"
                                                                + endDate
                                                                + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                                                + patientIdsInfant);

                                                List<Date> maxEnocunterDateTime = queryDate1.list();

                                                SQLQuery queryDate2 = session
                                                        .createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                                                + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                                                + endDate + "' and concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetReturnVisitDateConceptId())
                                                                + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                                                + patientIdsInfant);

                                                List<Date> maxReturnVisitDay = queryDate2.list();

                                                if (((maxReturnVisitDay.get(0)) != null)
                                                        && (maxEnocunterDateTime.get(0) != null)) {

                                                    if (((maxEnocunterDateTime.get(0)
                                                            .getTime()) >= threeMonthsBeforeEndDate.getTime()
                                                            && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                                                                    .getTime())
                                                            || ((maxReturnVisitDay.get(0)
                                                                    .getTime()) >= threeMonthsBeforeEndDate
                                                                            .getTime()
                                                                    && (maxReturnVisitDay.get(0)
                                                                            .getTime()) <= newEndDate.getTime())) {

                                                        patientsNotLostToFollowUp.add(patientId);

                                                    }

                                                    else {

                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }

                                                else if (((maxReturnVisitDay.get(0)) == null)
                                                        && (maxEnocunterDateTime.get(0) != null)) {

                                                    if (((maxEnocunterDateTime.get(0)
                                                            .getTime()) >= threeMonthsBeforeEndDate.getTime()
                                                            && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                                                                    .getTime())) {

                                                        patientsNotLostToFollowUp.add(patientId);

                                                    }

                                                    else {
                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }
                            }

                            if (HivTestResultConcept.get(0) == Integer
                                    .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                SQLQuery queryTestingStatusOfPartner = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "where ob.concept_id = "
                                                + Integer.parseInt(
                                                        GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                + " and pg.patient_id = " + patientId);

                                List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner.list();

                                if (patientIdsTestingStatusOfPartner.size() != 0) {

                                    SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                            .list();

                                    if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                .createSQLQuery(
                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetTestingStatusOfPartnerConceptId())
                                                                + " and o.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                + HivTestResultDate.get(0)
                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                + patientId);
                                        List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                .size() != 0) {

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .get(0) == Integer.parseInt(GlobalProperties
                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                        "select distinct rel.person_b from relationship rel "
                                                                + " inner join person pe on rel.person_b = pe.person_id "
                                                                + " inner join encounter en on rel.person_b = en.patient_id "
                                                                + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                + " where rel.person_a = " + patientId
                                                                + " and pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and pg.voided = 0 and pe.voided = 0 and rel.voided = 0 and rel.person_a = "
                                                                + patientId);

                                                List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                                if (infantHIVPositive.size() != 0) {

                                                    for (Integer patientIdsInfant : infantHIVPositive) {

                                                        SQLQuery queryInfantExited = session.createSQLQuery(
                                                                "select distinct o.person_id from obs o where o.concept_id = "
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetExitFromCareConceptId())
                                                                        + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                        + endDate
                                                                        + "' and o.voided = 0 and o.person_id="
                                                                        + patientIdsInfant);

                                                        List<Integer> patientIds2InfantExited = queryInfantExited
                                                                .list();

                                                        if (patientIds2InfantExited.size() == 0) {

                                                            SQLQuery queryDate1 = session.createSQLQuery(
                                                                    "select cast(max(encounter_datetime)as DATE) from encounter where "
                                                                            + "(select(cast(max(encounter_datetime)as Date))) <= '"
                                                                            + endDate
                                                                            + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                                                            + patientIdsInfant);

                                                            List<Date> maxEnocunterDateTime = queryDate1.list();

                                                            SQLQuery queryDate2 = session.createSQLQuery(
                                                                    "select cast(max(value_datetime) as DATE ) "
                                                                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                                                                            + endDate + "' and concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetReturnVisitDateConceptId())
                                                                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                                                            + patientIdsInfant);

                                                            List<Date> maxReturnVisitDay = queryDate2.list();

                                                            if (((maxReturnVisitDay.get(0)) != null)
                                                                    && (maxEnocunterDateTime.size() != 0)) {

                                                                if (((maxEnocunterDateTime.get(0)
                                                                        .getTime()) >= threeMonthsBeforeEndDate
                                                                                .getTime()
                                                                        && (maxEnocunterDateTime.get(0)
                                                                                .getTime()) <= newEndDate.getTime())
                                                                        || ((maxReturnVisitDay.get(0)
                                                                                .getTime()) >= threeMonthsBeforeEndDate
                                                                                        .getTime()
                                                                                && (maxReturnVisitDay.get(0)
                                                                                        .getTime()) <= newEndDate
                                                                                                .getTime())) {

                                                                    patientsNotLostToFollowUp.add(patientId);

                                                                }

                                                                else {
                                                                    patientIdsList.add(patientIdsInfant);
                                                                }
                                                            }

                                                            else if (((maxReturnVisitDay.get(0)) == null)
                                                                    && (maxEnocunterDateTime.size() != 0)) {

                                                                if (((maxEnocunterDateTime.get(0)
                                                                        .getTime()) >= threeMonthsBeforeEndDate
                                                                                .getTime()
                                                                        && (maxEnocunterDateTime.get(0)
                                                                                .getTime()) <= newEndDate
                                                                                        .getTime())) {

                                                                    patientsNotLostToFollowUp.add(patientId);

                                                                }

                                                                else {
                                                                    patientIdsList.add(patientIdsInfant);
                                                                }
                                                            }
                                                        }
                                                    }

                                                }

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersMalnourished(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> infantHivPosMothersMalnourishedList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersScreenedTbThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersScreenedTbThisMonthList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                            + endDate + "' and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetTBScreeningConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetTBScreeningConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetTBScreeningConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetTBScreeningConceptId())
                                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        patientIdsList.add(patientIdsInfant);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedAt18Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersTestedAt18MonthsList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt18MonthId())
                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                    + startDate
                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                            + endDate + "' and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery QueryInfantInPMTCTTestedAt18Months = session
                                                        .createSQLQuery(
                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                        + " where pg.program_id ="
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetPMTCTProgramId())
                                                                        + " and en.encounter_type = "
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetSerologyAt18MonthId())
                                                                        + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0  and en.patient_id = "
                                                                        + patientIdsInfant);

                                                List<Date> infantInPMTCTTestedAt18Months = QueryInfantInPMTCTTestedAt18Months
                                                        .list();

                                                if (infantInPMTCTTestedAt18Months.size() != 0) {

                                                    if ((infantInPMTCTTestedAt18Months.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (infantInPMTCTTestedAt18Months.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetSerologyAt9MonthId())
                                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery QueryInfantInPMTCTTestedAt18Months = session
                                                                        .createSQLQuery(
                                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                                        + " where pg.program_id ="
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId())
                                                                                        + " and en.encounter_type = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetSerologyAt18MonthId())
                                                                                        + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and en.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Date> infantInPMTCTTestedAt18Months = QueryInfantInPMTCTTestedAt18Months
                                                                        .list();

                                                                if (infantInPMTCTTestedAt18Months.size() != 0) {

                                                                    if ((infantInPMTCTTestedAt18Months.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (infantInPMTCTTestedAt18Months.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        patientIdsList.add(patientIdsInfant);
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedAt6Weeks(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersTestedAt6WeeksList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPCREncounterId())
                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                    + startDate
                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                            + endDate + "' and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery QueryInfantInPMTCTTestedAt6Weeks = session.createSQLQuery(
                                                        "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                + " where pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and en.encounter_type = "
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPCREncounterId())
                                                                + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and en.patient_id = "
                                                                + patientIdsInfant);

                                                List<Date> infantInPMTCTTestedAt6Weeks = QueryInfantInPMTCTTestedAt6Weeks
                                                        .list();

                                                if (infantInPMTCTTestedAt6Weeks.size() != 0) {

                                                    if ((infantInPMTCTTestedAt6Weeks.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (infantInPMTCTTestedAt6Weeks.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPCREncounterId())
                                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery QueryInfantInPMTCTTestedAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                                        + " where pg.program_id ="
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId())
                                                                                        + " and en.encounter_type = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPCREncounterId())
                                                                                        + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Date> infantInPMTCTTestedAt6Weeks = QueryInfantInPMTCTTestedAt6Weeks
                                                                        .list();

                                                                if (infantInPMTCTTestedAt6Weeks.size() != 0) {

                                                                    if ((infantInPMTCTTestedAt6Weeks.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (infantInPMTCTTestedAt6Weeks.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        patientIdsList.add(patientIdsInfant);
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedAt9Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersTestedAt9MonthsList(String startDate, String endDate)
            throws ParseException {
        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt9MonthId())
                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                    + startDate
                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery QueryInfantInPMTCTTestedAt9Months = session.createSQLQuery(
                                                        "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                + " where pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and en.encounter_type = "
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetSerologyAt9MonthId())
                                                                + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                + patientIdsInfant);

                                                List<Date> infantInPMTCTTestedAt9Months = QueryInfantInPMTCTTestedAt9Months
                                                        .list();

                                                if (infantInPMTCTTestedAt9Months.size() != 0) {

                                                    if ((infantInPMTCTTestedAt9Months.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (infantInPMTCTTestedAt9Months.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetSerologyAt9MonthId())
                                                                    + " and (select cast(min(en.encounter_datetime)as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (select cast(min(en.encounter_datetime)as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (cast(o.obs_datetime as DATE)) <= '"
                                                                            + endDate + "'"
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery QueryInfantInPMTCTTestedAt9Months = session
                                                                        .createSQLQuery(
                                                                                "select (cast(min(en.encounter_datetime)as DATE)) from encounter en "
                                                                                        + " inner join patient_program pg on en.patient_id = pg.patient_id "
                                                                                        + " where pg.program_id ="
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId())
                                                                                        + " and en.encounter_type = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetSerologyAt9MonthId())
                                                                                        + " and (select (cast(min(en.encounter_datetime)as DATE))) is not null and en.voided = 0 and pg.voided = 0 and en.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Date> infantInPMTCTTestedAt9Months = QueryInfantInPMTCTTestedAt9Months
                                                                        .list();

                                                                if (infantInPMTCTTestedAt9Months.size() != 0) {

                                                                    if ((infantInPMTCTTestedAt9Months.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (infantInPMTCTTestedAt9Months.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        patientIdsList.add(patientIdsInfant);
                                                                    }

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedPosAt18Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersTestedPosAt18MonthsList(String startDate, String endDate)
            throws ParseException {
        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt18MonthId())
                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                            + endDate + "' and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt18Months = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetResultForHIVTestConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate + "' and ob.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt18Months = queryInfantTestedPCRPosAt18Months
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt18Months.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetResultForHIVTestConceptId())
                                                                            + " and o.value_coded in ("
                                                                            + GlobalProperties
                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                .createSQLQuery(
                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                + Integer.parseInt(GlobalProperties
                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                + " and o.value_coded in ("
                                                                                + GlobalProperties
                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                + HivTestResultDate.get(0)
                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                + patientIdsInfant);
                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                .list();

                                                        if (HIVResultConceptForInfantTested.size() != 0) {

                                                            if (HIVResultConceptForInfantTested.get(0) == Integer
                                                                    .parseInt(GlobalProperties
                                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                patientIdsList.add(patientIdsInfant);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided =  0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetSerologyAt9MonthId())
                                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt9Months = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and ob.value_coded in ("
                                                                                        + GlobalProperties
                                                                                                .gpGetListOfAnswersToResultOfHIVTest()
                                                                                        + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt9Months = queryInfantTestedPCRPosAt9Months
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt9Months
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetResultForHIVTestConceptId())
                                                                                            + " and o.value_coded in ("
                                                                                            + GlobalProperties
                                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                                .createSQLQuery(
                                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                                + Integer.parseInt(
                                                                                                        GlobalProperties
                                                                                                                .gpGetResultForHIVTestConceptId())
                                                                                                + " and o.value_coded in ("
                                                                                                + GlobalProperties
                                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                                + HivTestResultDate
                                                                                                        .get(0)
                                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                                + patientIdsInfant);
                                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                                .list();

                                                                        if (HIVResultConceptForInfantTested
                                                                                .size() != 0) {

                                                                            if (HIVResultConceptForInfantTested
                                                                                    .get(0) == Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                                patientIdsList
                                                                                        .add(patientIdsInfant);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedPosAt6Weeks(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersTestedPosAt6WeeksList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetPCREncounterId())
                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetResultForHIVTestConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate + "' and ob.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetResultForHIVTestConceptId())
                                                                            + " and o.value_coded in ("
                                                                            + GlobalProperties
                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                .createSQLQuery(
                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                + Integer.parseInt(GlobalProperties
                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                + " and o.value_coded in ("
                                                                                + GlobalProperties
                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                + HivTestResultDate.get(0)
                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                + patientIdsInfant);
                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                .list();

                                                        if (HIVResultConceptForInfantTested.size() != 0) {

                                                            if (HIVResultConceptForInfantTested.get(0) == Integer
                                                                    .parseInt(GlobalProperties
                                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                patientIdsList.add(patientIdsInfant);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPCREncounterId())
                                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt6Weeks = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and ob.value_coded in ("
                                                                                        + GlobalProperties
                                                                                                .gpGetListOfAnswersToResultOfHIVTest()
                                                                                        + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt6Weeks = queryInfantTestedPCRPosAt6Weeks
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt6Weeks
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetResultForHIVTestConceptId())
                                                                                            + " and o.value_coded in ("
                                                                                            + GlobalProperties
                                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                                .createSQLQuery(
                                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                                + Integer.parseInt(
                                                                                                        GlobalProperties
                                                                                                                .gpGetResultForHIVTestConceptId())
                                                                                                + " and o.value_coded in ("
                                                                                                + GlobalProperties
                                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                                + HivTestResultDate
                                                                                                        .get(0)
                                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                                + patientIdsInfant);
                                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                                .list();

                                                                        if (HIVResultConceptForInfantTested
                                                                                .size() != 0) {

                                                                            if (HIVResultConceptForInfantTested
                                                                                    .get(0) == Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                                patientIdsList
                                                                                        .add(patientIdsInfant);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTestedPosAt9Months(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivPosMothersTestedPosAt9MonthsList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and en.encounter_type = "
                                                    + Integer.parseInt(GlobalProperties.gpGetSerologyAt9MonthId())
                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                    + endDate
                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                                            + "'" + " and o.voided = 0 and o.person_id="
                                                            + patientIdsInfant);

                                            List<Integer> patientIds2InfantExited = queryInfantExited.list();

                                            if (patientIds2InfantExited.size() == 0) {

                                                SQLQuery queryInfantTestedPCRPosAt9Months = session.createSQLQuery(
                                                        "select distinct pg.patient_id from patient_program pg "
                                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                + "where ob.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetResultForHIVTestConceptId())
                                                                + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                + startDate
                                                                + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                + endDate + "' and ob.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                + endDate
                                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                + " and pg.patient_id = " + patientIdsInfant);

                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt9Months = queryInfantTestedPCRPosAt9Months
                                                        .list();

                                                if (patientIdsQueryInfantTestedPCRPosAt9Months.size() != 0) {

                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                            .createSQLQuery(
                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetResultForHIVTestConceptId())
                                                                            + " and o.value_coded in ("
                                                                            + GlobalProperties
                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                            .list();

                                                    if ((HIVResultDateForInfantTested.get(0)
                                                            .getTime() >= newStartDate.getTime())
                                                            && (HIVResultDateForInfantTested.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                .createSQLQuery(
                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                + Integer.parseInt(GlobalProperties
                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                + " and o.value_coded in ("
                                                                                + GlobalProperties
                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                + HivTestResultDate.get(0)
                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                + patientIdsInfant);
                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                .list();

                                                        if (HIVResultConceptForInfantTested.size() != 0) {

                                                            if (HIVResultConceptForInfantTested.get(0) == Integer
                                                                    .parseInt(GlobalProperties
                                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                patientIdsList.add(patientIdsInfant);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + " where rel.person_a = " + patientId
                                                                    + " and pg.program_id ="
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())
                                                                    + " and en.encounter_type = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetSerologyAt9MonthId())
                                                                    + " and (select cast(en.encounter_datetime as DATE)) <= '"
                                                                    + endDate
                                                                    + "' and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                    + patientId);

                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                            + endDate
                                                                            + "' and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryInfantTestedPCRPosAt9Months = session
                                                                        .createSQLQuery(
                                                                                "select distinct pg.patient_id from patient_program pg "
                                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                                        + "where ob.concept_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetResultForHIVTestConceptId())
                                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                                        + startDate
                                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and ob.value_coded in ("
                                                                                        + GlobalProperties
                                                                                                .gpGetListOfAnswersToResultOfHIVTest()
                                                                                        + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                                                        + endDate
                                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                                        + " and pg.patient_id = "
                                                                                        + patientIdsInfant);

                                                                List<Integer> patientIdsQueryInfantTestedPCRPosAt9Months = queryInfantTestedPCRPosAt9Months
                                                                        .list();

                                                                if (patientIdsQueryInfantTestedPCRPosAt9Months
                                                                        .size() != 0) {

                                                                    SQLQuery queryHIVResultDateForInfantTested = session
                                                                            .createSQLQuery(
                                                                                    "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                            + Integer.parseInt(
                                                                                                    GlobalProperties
                                                                                                            .gpGetResultForHIVTestConceptId())
                                                                                            + " and o.value_coded in ("
                                                                                            + GlobalProperties
                                                                                                    .gpGetListOfAnswersToResultOfHIVTest()
                                                                                            + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                            + endDate
                                                                                            + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                                            + patientIdsInfant);

                                                                    List<Date> HIVResultDateForInfantTested = queryHIVResultDateForInfantTested
                                                                            .list();

                                                                    if ((HIVResultDateForInfantTested.get(0)
                                                                            .getTime() >= newStartDate.getTime())
                                                                            && (HIVResultDateForInfantTested.get(0)
                                                                                    .getTime() <= newEndDate
                                                                                            .getTime())) {

                                                                        SQLQuery queryHIVResultConceptForInfantTested = session
                                                                                .createSQLQuery(
                                                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                                                + Integer.parseInt(
                                                                                                        GlobalProperties
                                                                                                                .gpGetResultForHIVTestConceptId())
                                                                                                + " and o.value_coded in ("
                                                                                                + GlobalProperties
                                                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                                                + HivTestResultDate
                                                                                                        .get(0)
                                                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                                                + patientIdsInfant);
                                                                        List<Integer> HIVResultConceptForInfantTested = queryHIVResultConceptForInfantTested
                                                                                .list();

                                                                        if (HIVResultConceptForInfantTested
                                                                                .size() != 0) {

                                                                            if (HIVResultConceptForInfantTested
                                                                                    .get(0) == Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                                                patientIdsList
                                                                                        .add(patientIdsInfant);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivPosMothersTherapFood(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> infantHivPosMothersTherapFoodList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newInfantHivPosMothersNvpAztAtBirth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> newInfantHivPosMothersNvpAztAtBirthList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#reportedDeadInfantHivPosMothers(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> reportedDeadInfantHivPosMothersList(String startDate, String endDate)
            throws ParseException {

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                    SQLQuery infantHIVPositiveInPMTCT = session
                                            .createSQLQuery("select distinct rel.person_b from relationship rel "
                                                    + " inner join person pe on rel.person_b = pe.person_id "
                                                    + " inner join encounter en on rel.person_b = en.patient_id "
                                                    + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                    + " where rel.person_a = " + patientId + " and pg.program_id ="
                                                    + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                                                    + " and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                    + patientId);

                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                    if (infantHIVPositive.size() != 0) {

                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                            SQLQuery queryInfantDied = session.createSQLQuery(
                                                    "select distinct pg.patient_id from patient_program pg "
                                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                            + "where ob.concept_id = "
                                                            + Integer.parseInt(
                                                                    GlobalProperties.gpGetExitFromCareConceptId())
                                                            + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                            + startDate
                                                            + "' and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and ob.value_coded = "
                                                            + GlobalProperties.gpGetExitFromCareDiedConceptId()
                                                            + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                            + " and pg.patient_id = " + patientIdsInfant);

                                            List<Integer> patientIdsQueryInfantDied = queryInfantDied.list();

                                            if (patientIdsQueryInfantDied.size() != 0) {

                                                SQLQuery queryHIVResultDateForInfantDied = session.createSQLQuery(
                                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetExitFromCareConceptId())
                                                                + " and o.value_coded = "
                                                                + GlobalProperties.gpGetExitFromCareDiedConceptId()
                                                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                + endDate
                                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                                + patientIdsInfant);

                                                List<Date> HIVResultDateForInfantDied = queryHIVResultDateForInfantDied
                                                        .list();

                                                if (HIVResultDateForInfantDied.size() != 0) {

                                                    if ((HIVResultDateForInfantDied.get(0).getTime() >= newStartDate
                                                            .getTime())
                                                            && (HIVResultDateForInfantDied.get(0)
                                                                    .getTime() <= newEndDate.getTime())) {

                                                        patientIdsList.add(patientIdsInfant);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (HivTestResultConcept.get(0) == Integer
                                    .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                SQLQuery queryTestingStatusOfPartner = session
                                        .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                + "inner join obs ob on pg.patient_id = ob.person_id "
                                                + "inner join person pe on pg.patient_id = pe.person_id "
                                                + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                + "where ob.concept_id = "
                                                + Integer.parseInt(
                                                        GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                + "' and ob.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                + " and pg.patient_id = " + patientId);

                                List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner.list();

                                if (patientIdsTestingStatusOfPartner.size() != 0) {

                                    SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                    + endDate
                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                    + patientId);
                                    List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                            .list();

                                    if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                .createSQLQuery(
                                                        "select o.value_coded from obs o where o.concept_id = "
                                                                + Integer.parseInt(GlobalProperties
                                                                        .gpGetTestingStatusOfPartnerConceptId())
                                                                + " and o.value_coded in ("
                                                                + GlobalProperties
                                                                        .gpGetListOfAnswersToResultOfHIVTest()
                                                                + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                + HivTestResultDate.get(0)
                                                                + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                + patientId);
                                        List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                .size() != 0) {

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .get(0) == Integer.parseInt(GlobalProperties
                                                            .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                        "select distinct rel.person_b from relationship rel "
                                                                + " inner join person pe on rel.person_b = pe.person_id "
                                                                + " inner join encounter en on rel.person_b = en.patient_id "
                                                                + " inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                + " where rel.person_a = " + patientId
                                                                + " and pg.program_id ="
                                                                + Integer.parseInt(
                                                                        GlobalProperties.gpGetPMTCTProgramId())
                                                                + " and rel.voided = 0 and pe.voided = 0 and en.voided = 0 and pg.voided = 0 and rel.person_a = "
                                                                + patientId);

                                                List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT.list();

                                                if (infantHIVPositive.size() != 0) {

                                                    for (Integer patientIdsInfant : infantHIVPositive) {

                                                        SQLQuery queryInfantDied = session.createSQLQuery(
                                                                "select distinct pg.patient_id from patient_program pg "
                                                                        + "inner join obs ob on pg.patient_id = ob.person_id "
                                                                        + "inner join person pe on pg.patient_id = pe.person_id "
                                                                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                                        + "where ob.concept_id = "
                                                                        + Integer.parseInt(GlobalProperties
                                                                                .gpGetExitFromCareConceptId())
                                                                        + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                                        + startDate
                                                                        + "' and (cast(ob.obs_datetime as DATE)) <= '"
                                                                        + endDate + "' and ob.value_coded = "
                                                                        + GlobalProperties
                                                                                .gpGetExitFromCareDiedConceptId()
                                                                        + " and (cast(pg.date_enrolled as DATE)) <= '"
                                                                        + endDate
                                                                        + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                                        + " and pg.patient_id = "
                                                                        + patientIdsInfant);

                                                        List<Integer> patientIdsQueryInfantDied = queryInfantDied
                                                                .list();

                                                        if (patientIdsQueryInfantDied.size() != 0) {

                                                            SQLQuery queryHIVResultDateForInfantDied = session
                                                                    .createSQLQuery(
                                                                            "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                                                    + Integer.parseInt(
                                                                                            GlobalProperties
                                                                                                    .gpGetExitFromCareConceptId())
                                                                                    + " and o.value_coded = "
                                                                                    + GlobalProperties
                                                                                            .gpGetExitFromCareDiedConceptId()
                                                                                    + " and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                                                    + endDate
                                                                                    + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.value and o.person_id="
                                                                                    + patientIdsInfant);

                                                            List<Date> HIVResultDateForInfantDied = queryHIVResultDateForInfantDied
                                                                    .list();

                                                            if ((HIVResultDateForInfantDied.get(0)
                                                                    .getTime() >= newStartDate.getTime())
                                                                    && (HIVResultDateForInfantDied.get(0)
                                                                            .getTime() <= newEndDate.getTime())) {

                                                                patientIdsList.add(patientIdsInfant);

                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                    }

                                }
                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosBreastFeeding(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosBreastFeedingList(String startDate, String endDate) throws ParseException {
        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select cast(encounter_datetime as DATE)) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds4 = query3.list();

                            if (patientIds4.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                    + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            SQLQuery queryHIVPosWomenBreastFeeding = session.createSQLQuery(
                                                    "select distinct pg.patient_id from patient_program pg "
                                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                            + "where ob.concept_id = "
                                                            + Integer.parseInt(GlobalProperties
                                                                    .gpGetInfantFeedingMethodConceptId())
                                                            + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                            + startDate
                                                            + "' and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and ob.value_coded IN ("
                                                            + GlobalProperties
                                                                    .gpGetBreastedPredominatelyConceptIdConceptId()
                                                            + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                            + endDate
                                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                            + " and pg.patient_id = " + patientId);

                                            List<Integer> patientIdsOfHIVPosWomenBreastFeeding = queryHIVPosWomenBreastFeeding
                                                    .list();

                                            if (patientIdsOfHIVPosWomenBreastFeeding.size() != 0)

                                            {

                                                patientIdsList.add(patientId);

                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosUsingFormula(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosUsingFormulaList(String startDate, String endDate) throws ParseException {
        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join obs ob on pg.patient_id = ob.person_id "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join encounter enc on pg.patient_id = enc.patient_id " + "where enc.encounter_type= "
                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId()) + " and ob.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetDateOfConfinementConceptId())
                    + " and (cast(enc.encounter_datetime as DATE)) >= '" + startDate
                    + "' AND (cast(enc.encounter_datetime as DATE)) <= '" + endDate
                    + "' and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                    + " and enc.voided=0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {
                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryEstimatedDateOfDelivery = session.createSQLQuery(
                            "select cast(encounter_datetime as DATE) from encounter where encounter_type = "
                                    + Integer.parseInt(GlobalProperties.gpGetMaternityEncounterId())
                                    + " and (select cast(encounter_datetime as DATE)) is not null and voided = 0 and patient_id= "
                                    + patientId);
                    List<Date> dateOfDelivery = queryEstimatedDateOfDelivery.list();

                    if (dateOfDelivery.size() != 0) {

                        if ((dateOfDelivery.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDelivery.get(0).getTime() <= newEndDate.getTime())) {

                            SQLQuery query3 = session
                                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                            + "where ob.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                            + "' and ob.value_coded IN ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                            + " and pg.patient_id = " + patientId);

                            List<Integer> patientIds4 = query3.list();

                            if (patientIds4.size() != 0) {

                                SQLQuery queryHIVResultDate = session.createSQLQuery(
                                        "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                + Integer
                                                        .parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                                + " and o.value_coded in ("
                                                + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                + patientId);
                                List<Date> HivTestResultDate = queryHIVResultDate.list();

                                if (HivTestResultDate.size() != 0)

                                {

                                    SQLQuery queryHIVResultConcept = session
                                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetResultForHIVTestConceptId())
                                                    + " and o.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                    + HivTestResultDate.get(0)
                                                    + "' and o.voided = 0 and o.person_id= " + patientId);
                                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                                    if (HivTestResultConcept.size() != 0) {

                                        if (HivTestResultConcept.get(0) == Integer.parseInt(
                                                GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                                            SQLQuery queryHIVPosWomenBreastFeeding = session.createSQLQuery(
                                                    "select distinct pg.patient_id from patient_program pg "
                                                            + "inner join obs ob on pg.patient_id = ob.person_id "
                                                            + "inner join person pe on pg.patient_id = pe.person_id "
                                                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                            + "where ob.concept_id = "
                                                            + Integer.parseInt(GlobalProperties
                                                                    .gpGetInfantFeedingMethodConceptId())
                                                            + " and (cast(ob.obs_datetime as DATE)) >= '"
                                                            + startDate
                                                            + "' and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                            + "' and ob.value_coded IN ("
                                                            + GlobalProperties
                                                                    .gpGetBreastedPredominatelyConceptIdConceptId()
                                                            + ") and (cast(pg.date_enrolled as DATE)) <= '"
                                                            + endDate
                                                            + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                            + " and pg.patient_id = " + patientId);

                                            List<Integer> patientIdsOfHIVPosWomenBreastFeeding = queryHIVPosWomenBreastFeeding
                                                    .list();

                                            if (patientIdsOfHIVPosWomenBreastFeeding.size() != 0)

                                            {

                                                patientIdsList.add(patientId);

                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    // ---------D. Family Planning Data Elements----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosExpectedFpAtFacility(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosExpectedFpAtFacilityList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personExpectedAtFacilityIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetEstimatedDateOfCOnfinementId())
                        + "' AND (cast(ob.value_datetime as DATE)) >= '" + startDate + "'"
                        + " AND (cast(ob.value_datetime as DATE)) <= '" + endDate + "' ")
                .list();
        List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId()) + "' ")
                .list();
        List<Integer> patientInEncounterIds = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                .list();

        for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
            for (Integer personExpectedAtFacilityId : personExpectedAtFacilityIds) {
                if (personExpectedAtFacilityId.equals(personFemaleWithHIVPosId))
                    for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                        for (Integer patientInEncounterId : patientInEncounterIds) {

                            if (personExpectedAtFacilityId.equals(patientInEncounterId)
                                    && personExpectedAtFacilityId.equals(personFemaleWithHIVPosId)
                                    && personExpectedAtFacilityId.equals(personInFamilyPlanningId)) {

                                Person person = Context.getPersonService().getPerson(personFemaleWithHIVPosId);
                                persons.add(person);
                            }
                        }
                    }
            }
        }
        return persons;
    }

    /**
     * Number of HIV positive women seen in family planning
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosSeenInFp(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosSeenInFpList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> patientInEncounterIds = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                .list();
        List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId())
                        + "' AND (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                        + " AND (cast(ob.obs_datetime as DATE)) <= '" + endDate + "' ")
                .list();

        for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
            for (int patientInProgramId : patientInProgramIds) {
                if (personFemaleWithHIVPosId.equals(patientInProgramId))

                    for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                        for (int patientInEncounterId : patientInEncounterIds) {

                            if (personInFamilyPlanningId.equals(personFemaleWithHIVPosId)
                                    && personInFamilyPlanningId.equals(patientInProgramId)
                                    && personInFamilyPlanningId.equals(patientInEncounterId)) {
                                Person person = Context.getPersonService().getPerson(personInFamilyPlanningId);
                                persons.add(person);
                            }
                        }
                    }
            }
        }
        return persons;
    }

    /**
     * Number of HIV positive women partners seen in family planning
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosPartnersSeenInFp(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosPartnersSeenInFpList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs ob on p.person_id=ob.person_id where ob.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId())
                        + "' AND (cast(ob.obs_datetime as DATE)) >= '" + startDate + "'"
                        + " AND (cast(ob.obs_datetime as DATE)) <= '" + endDate + "' ")
                .list();
        List<Integer> partnerInFamilyPlanningIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetTestingStatusOfPartnerId())
                        + "' and (cast(o.obs_datetime as DATE)) <= '" + endDate + "' ")
                .list();
        List<Integer> patientEncounterIds = session.createSQLQuery(
                "select distinct pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id")
                .list();

        for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
            for (Integer personInProgramId : patientInProgramIds) {
                if (personInProgramId.equals(personFemaleWithHIVPosId))
                    for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                        for (Integer partnerInFamilyPlanningId : partnerInFamilyPlanningIds) {
                            if (personInFamilyPlanningId.equals(partnerInFamilyPlanningId))
                                for (Integer patientEncounterId : patientEncounterIds) {

                                    if (personInProgramId.equals(personFemaleWithHIVPosId)
                                            && personInProgramId.equals(patientEncounterId)
                                            && personInProgramId.equals(personInFamilyPlanningId)
                                            && personInProgramId.equals(partnerInFamilyPlanningId)) {

                                        Person person = Context.getPersonService().getPerson(personInProgramId);
                                        persons.add(person);
                                    }
                                }
                        }
                    }
            }
        }
        return persons;
    }

    /**
     * @see 
     *      org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#(
     *      java.lang.String, java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosReceivingModernContraceptiveList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                        + "' and p.voided=false")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate
                        + "' AND pp.date_completed is null ")
                .list();
        List<Integer> personInFamilyPlanningIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetMethodOfFamilyPlanningId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetInjectableContraceptivesId())
                        + "' or o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetOralContraceptionId())
                        + "' or o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetCondomsId())
                        + "' AND (cast(o.obs_datetime as DATE)) >= '" + startDate + "'"
                        + " AND (cast(o.obs_datetime as DATE)) <= '" + endDate + "' ")
                .list();
        List<Integer> patientEncounterIds = session.createSQLQuery(
                "select distinct pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id")
                .list();

        for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
            for (Integer patientInProgramId : patientInProgramIds)
                if (patientInProgramId.equals(personFemaleWithHIVPosId))
                    for (Integer personInFamilyPlanningId : personInFamilyPlanningIds) {
                        for (Integer patientEncounterId : patientEncounterIds) {

                            if (patientInProgramId.equals(personFemaleWithHIVPosId)
                                    && patientInProgramId.equals(patientEncounterId)
                                    && patientInProgramId.equals(personInFamilyPlanningId)) {
                                Person person = Context.getPersonService().getPerson(patientInProgramId);
                                persons.add(person);
                            }
                        }
                    }
        }
        return persons;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#womenHivPosRefferedForFp(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> womenHivPosRefferedForFpList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personFemaleWithHIVPosIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F' and  o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())
                        + "' and p.voided=false ")
                .list();
        List<Integer> personReferredForFpIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetDispositionId()) + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetReferredForFamilyPlanningId())
                        + "' AND (cast(o.obs_datetime as DATE)) >= '" + startDate + "'"
                        + " AND (cast(o.obs_datetime as DATE)) <= '" + endDate + "' ")
                .list();
        List<Integer> patientEncounterIds = session.createSQLQuery(
                "select distinct pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id")
                .list();
        for (Integer personFemaleWithHIVPosId : personFemaleWithHIVPosIds) {
            for (Integer personReferredForFp : personReferredForFpIds) {
                if (personReferredForFp.equals(personFemaleWithHIVPosId))
                    for (Integer patientEncounterId : patientEncounterIds)
                        if (personReferredForFp.equals(personFemaleWithHIVPosId)
                                && personReferredForFp.equals(patientEncounterId)) {
                            Person person = Context.getPersonService().getPerson(personReferredForFp);
                            persons.add(person);
                        }
            }
        }
        return persons;
    }

    // ------------E. Submit VCT Data Elements-----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#couplesCounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> couplesCounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personCoupledIds = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling=2 and p.voided=false and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' AND p.gender='M' and p.voided = 0 and t.voided = 0 ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0 ")
                .list();
        for (Integer personCoupledId : personCoupledIds) {
            for (Integer personTestedId : personTested) {
                if (personTestedId.equals(personCoupledId)) {
                    Person person = Context.getPersonService().getPerson(personTestedId);
                    persons.add(person);
                }
            }
        }

        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#discordantCouples2(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> discordantCouples2List(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> coupleCounseledTestedIds = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id inner join trac_sample_test ts on t.code_test=ts.sample_code where ts.voided=0 and t.vct_or_pit=0 and t.type_of_counseling=2 and p.voided=false and t.partner_id is not null ")
                .list();

        List<Integer> discordantCoupleMalePartnerIds = session.createSQLQuery(
                "select distinct t.client_id from trac_vct_client t inner join obs o on t.client_id-o.person_id where o.concept_id='2169' and o.value_coded='664' ")
                .list();
        List<Integer> discordantCoupleMaleInfectedIds = session.createSQLQuery(
                "Select distinct t.partner_id from trac_vct_client t inner join obs o on t.client_id=o.person_id where o.concept_id='2169' and o.value_coded='703' ")
                .list();

        @SuppressWarnings("unused")
        List<Integer> discordantCoupleFemalePartnerInfectedIds = session.createSQLQuery(
                "select distinct t.client_id from trac_vct_client t inner join obs o on t.client_id-o.person_id where o.concept_id='2169' and o.value_coded='703' ")
                .list();
        @SuppressWarnings("unused")
        List<Integer> discordantCoupleFemaleInfectedIds = session.createSQLQuery(
                "Select distinct t.partner_id from trac_vct_client t inner join obs o on t.client_id=o.person_id where o.concept_id='2169' and o.value_coded='664' ")
                .list();

        for (Integer coupleCounseledTestedId : coupleCounseledTestedIds) {
            for (Integer discordantCoupleMalePartnerId : discordantCoupleMalePartnerIds) {
                for (Integer discordantCoupleMaleInfectedId : discordantCoupleMaleInfectedIds) {
                    if (coupleCounseledTestedId.equals(discordantCoupleMalePartnerId)
                            && coupleCounseledTestedId.equals(discordantCoupleMaleInfectedId)) {

                        // for (Integer
                        // discordantCoupleFemalePartnerInfectedId:discordantCoupleFemalePartnerInfectedIds){
                        // for(Integer
                        // discordantCoupleFemaleInfectedId:discordantCoupleFemaleInfectedIds)
                        // {
                        Person person = Context.getPersonService().getPerson(coupleCounseledTestedId);
                        persons.add(person);

                    }
                }
            }
        }
        // }
        // }

        return persons;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleHivPosMoreThan25(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleHivPosMoreThan25List(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleHivPosUnder15to24(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleHivPosUnder15to24List(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "',pe.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',pe.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of HIV positive female clients(age <15)
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleHivPosUnderFifteen(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleHivPosUnderFifteenList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleHivPosMoreThan25(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleHivPosMoreThan25List(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleHivPosUnder15to24(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleHivPosUnder15to24List(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "',pe.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',pe.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleHivPosUnderFifteen(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleHivPosUnderFifteenList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new female clients(age 15-24) tested and received result
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemale15To24TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemale15To24TestReceiveResList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personFemaleId)) {
                    for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                        if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                && personTestedAndReceivedResultId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedAndReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleFifteenTo24CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleFifteenTo24CounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new Female clients (age 25+) counseled and tested for HIV
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleMore25CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleMore25CounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleMore25TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleMore25TestReceiveResList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                if (personCounseledAndTestsedId.equals(personFemaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                && personReceivedResultId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleUnderFifteenCounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleUnderFifteenCounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newFemaleUnderFifteenTestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newFemaleUnderFifteenTestReceiveResList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new male clients(age 15-24) tested and received results
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMale15To24TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMale15To24TestReceiveResList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voideed = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                        if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                && personTestedAndReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedAndReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleFifteenTo24CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleFifteenTo24CounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleMore25CounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleMore25CounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new male clients (age 25 +) tested and received results
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleMore25TestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleMore25TestReceiveResList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                if (personCounseledAndTestsedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new male clients counselled and tested for
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleUnderFifteenCounseledTested(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleUnderFifteenCounseledTestedList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new males clients (age <15)tested and received results
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleUnderFifteenTestReceiveRes(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleUnderFifteenTestReceiveResList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=0 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    // ----------F. Provider-Initiated Testing (PIT) Data Elements----------

    /**
     * Number of new female clients (age 15-24) counseled and tested for HIV
     * through PIT
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#female15To24CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> female15To24CounseledThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId()) + " and p.voided = 0 ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#female15To24HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> female15To24HivPosThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "',pe.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',pe.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#female15To24HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> female15To24HivResThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='F'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personFemaleId)) {
                    for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                        if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                && personTestedAndReceivedResultId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedAndReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThan25CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleMoreThan25CounseledThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThan25HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleMoreThan25HivPosThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleMoreThan25HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleMoreThan25HivResThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                if (personCounseledAndTestsedId.equals(personFemaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                && personReceivedResultId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleUnderFifteenCounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleUnderFifteenCounseledThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', p.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND p.voided = 0 and o.voided = 0 AND p.gender = 'F' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleUnderFifteenHivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleUnderFifteenHivPosThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#femaleUnderFifteenHivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> femaleUnderFifteenHivResThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personFemaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'F' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0 ")
                .list();

        for (Integer personFemaleId : personFemaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personFemaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personFemaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#male15To24CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> male15To24CounseledThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#male15To24HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> male15To24HivPosThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "',pe.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',pe.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * Number of new males clients(ages 15-24) who received HIV results through
     * PIT
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#male15To24HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> male15To24HivResThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.gender='M'and DATEDIFF('"
                        + endDate + "',p.birthdate) >= " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " and DATEDIFF('" + endDate + "',p.birthdate) <= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFourYearsId())
                        + " and p.voided= 0 and o.voided = 0 and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 AND t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTestedAndReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personTestedAndReceivedResultId : personTestedAndReceivedResultIds) {
                        if (personTestedAndReceivedResultId.equals(personCounseledAndTestedId)
                                && personTestedAndReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedAndReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThan25CounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleMoreThan25CounseledThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThan25HivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleMoreThan25HivPosThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and pe.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleMoreThan25HivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleMoreThan25HivResThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) >= "
                        + Integer.parseInt(GlobalProperties.gpGetTwentyFiveYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseledAndTestsedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestsedId : personCounseledAndTestsedIds) {
                if (personCounseledAndTestsedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestsedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleUnderFifteenCounseledThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleUnderFifteenCounseledThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', p.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND p.voided = 0 and o.voided = 0 AND p.gender = 'M' ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct person_id from person p inner join trac_vct_client t on p.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and p.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleUnderFifteenHivPosThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleUnderFifteenHivPosThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and pe.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseledAndTestedIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personReceivedResultIds = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledAndTestedId : personCounseledAndTestedIds) {
                if (personCounseledAndTestedId.equals(personMaleId)) {
                    for (Integer personReceivedResultId : personReceivedResultIds) {
                        if (personReceivedResultId.equals(personCounseledAndTestedId)
                                && personReceivedResultId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personReceivedResultId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#maleUnderFifteenHivResThroughPit(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> maleUnderFifteenHivResThroughPitList(String startDate, String endDate) {
        List<Person> persons = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personMaleIds = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join obs o on pe.person_id=o.person_id WHERE DATEDIFF('"
                        + endDate + "', pe.birthdate) < " + Integer.parseInt(GlobalProperties.gpGetFifteenYearsId())
                        + " AND pe.voided = 0 and o.voided = 0 AND pe.gender = 'M' and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'  ")
                .list();
        List<Integer> personCounseled = session.createSQLQuery(
                "SELECT distinct pe.person_id from person pe inner join trac_vct_client t on pe.person_id=t.client_id where t.vct_or_pit=1 and t.type_of_counseling is not null and pe.voided = 0 and t.voided = 0 and t.date_registration between '"
                        + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personTested = session.createSQLQuery(
                "SELECT distinct t.client_id from trac_vct_client t where t.code_test is not null and t.voided=0 ")
                .list();

        for (Integer personMaleId : personMaleIds) {
            for (Integer personCounseledId : personCounseled) {
                if (personCounseledId.equals(personMaleId)) {
                    for (Integer personTestedId : personTested) {
                        if (personTestedId.equals(personCounseledId) && personTestedId.equals(personMaleId)) {

                            Person person = Context.getPersonService().getPerson(personTestedId);
                            persons.add(person);
                        }
                    }
                }
            }
        }
        return persons;

    }

    // ----------G. PEP Data Elements----------

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOccupExpo3MonthAfterPep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivOccupExpo3MonthAfterPepList(String startDate, String endDate) {
        List<Person> patients = new ArrayList<Person>();
        Session session = getSessionFactory().getCurrentSession();

        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                "SELECT  DISTINCT enc.patient_id FROM encounter enc inner join obs ob on ob.person_id=enc.patient_id where ob.concept_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "'")
                .list();
        List<Integer> personAtRiskExposedIds = session.createSQLQuery(
                "SELECT DISTINCT p.patient_id from patient p inner join obs o on p.patient_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetExposureToBloodOrBloodProductId()) + "' ")
                .list();
        List<Integer> personOnArvDrugIds = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                        + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                        + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                .list();

        for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
            for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
                if (personEnrolledInPepId.equals(personEnrolledInPepPRogramAtRiskOfOcupationExposureId))
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                            if (patientInProgramId.equals(personOnEncountersWithId))
                                for (Integer personAtRiskExposedId : personAtRiskExposedIds) {
                                    for (Integer personOnArvDrugId : personOnArvDrugIds) {
                                        if ((personEnrolledInPepId
                                                .equals(personEnrolledInPepPRogramAtRiskOfOcupationExposureId)
                                                && personEnrolledInPepId.equals(patientInProgramId))
                                                && personEnrolledInPepId.equals(personOnEncountersWithId)
                                                && personEnrolledInPepId.equals(personAtRiskExposedId)
                                                && personEnrolledInPepId.equals(personOnArvDrugId)) {

                                            Person person = Context.getPersonService()
                                                    .getPerson(personEnrolledInPepId);
                                            patients.add(person);
                                        }
                                    }
                                }
                        }
                    }
            }
        }
        return patients;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOccupationExposure(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivOccupationExposureList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> patientInEncounterIds = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                .list();
        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetExposureToBloodOrBloodProductId()) + "' ")
                .list();

        for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                if (personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId))
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                            for (Integer patientInEncounterId : patientInEncounterIds) {

                                if ((personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                        .equals(personEnrolledInPepId)
                                        && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                .equals(patientInEncounterId)
                                        && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                .equals(patientInProgramId))
                                        && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                .equals(personAtRiskOnPEPId)) {

                                    Person person = Context.getPersonService()
                                            .getPerson(personEnrolledInPepPRogramAtRiskOfOcupationExposureId);
                                    patients.add(person);
                                }
                            }
                        }
                    }
            }
        }
        return patients;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of
     * occupational exposure who received PEP
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOccupationExposurePep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivOccupationExposurePepList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp inner join encounter enc on pp.patient_id=enc.patient_id")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetExposureToBloodOrBloodProductId()) + "' ")
                .list();
        List<Integer> personOnArvDrug = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                        + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                        + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                .list();

        for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                if (personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId))
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                            if (patientInProgramId.equals(personAtRiskOnPEPId))
                                for (Integer personOnArvDrugId : personOnArvDrug) {
                                    for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                        if ((personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                .equals(personEnrolledInPepId)
                                                && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                        .equals(patientInProgramId))
                                                && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                        .equals(personAtRiskOnPEPId)
                                                && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                        .equals(personOnArvDrugId)
                                                && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                                        .equals(personOnEncountersWithId)) {

                                            Person person = Context.getPersonService().getPerson(
                                                    personEnrolledInPepPRogramAtRiskOfOcupationExposureId);
                                            patients.add(person);
                                        }
                                    }
                                }
                        }
                    }
            }
        }
        return patients;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOtherNoneOccupExpo3MonthAfterPep(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> newAtRiskHivOtherNoneOccupExpo3MonthAfterPepList(String startDate, String endDate) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOtherNoneOccupationExposure(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivOtherNoneOccupationExposureList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personEnrolledInPepPRogramAtRiskOfNonOcupationExposureIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> patientInEncounterIds = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join encounter enc on pat.patient_id=enc.patient_id ")
                .list();
        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetSexualContactWithHivPositivePatient()) + "' ")
                .list();

        for (Integer personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId : personEnrolledInPepPRogramAtRiskOfNonOcupationExposureIds) {
            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                if (personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId.equals(personEnrolledInPepId))
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                            for (Integer patientInEncounterId : patientInEncounterIds) {

                                if ((personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                        .equals(personEnrolledInPepId)
                                        && personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                                .equals(patientInEncounterId)
                                        && personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                                .equals(patientInProgramId))
                                        && personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId
                                                .equals(personAtRiskOnPEPId)) {

                                    Person person = Context.getPersonService()
                                            .getPerson(personEnrolledInPepPRogramAtRiskOfNonOcupationExposureId);
                                    patients.add(person);
                                }
                            }
                        }
                    }
            }
        }
        return patients;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of other
     * non-occupational exposure who received PEP
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivOtherNoneOccupationExposurePep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivOtherNoneOccupationExposurePepList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp inner join encounter enc on pp.patient_id=enc.patient_id")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='"
                        + Integer.parseInt(GlobalProperties.gpGetSexualContactWithHivPositivePatient()) + "' ")
                .list();
        List<Integer> personOnArvDrug = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                        + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                        + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                .list();

        for (Integer personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId : personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureIds) {
            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                if (personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId.equals(personEnrolledInPepId))
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                            if (patientInProgramId.equals(personAtRiskOnPEPId))
                                for (Integer personOnArvDrugId : personOnArvDrug) {
                                    for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                        if ((personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                .equals(personEnrolledInPepId)
                                                && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                        .equals(patientInProgramId))
                                                && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                        .equals(personAtRiskOnPEPId)
                                                && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                        .equals(personOnArvDrugId)
                                                && personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId
                                                        .equals(personOnEncountersWithId)) {

                                            Person person = Context.getPersonService().getPerson(
                                                    personEnrolledInPepPRogramAtRiskOfNonOcuppationalExposureId);
                                            patients.add(person);
                                        }
                                    }
                                }
                        }
                    }
            }
        }
        return patients;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of rape/
     * sexual assault
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivRapeAssault(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivRapeAssaultList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personEnrolledInPepPRogramAtRiskOfOcupationExposureIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                "SELECT distinct p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetSexualAssaultId())
                        + "' ")
                .list();

        for (Integer personEnrolledInPepPRogramAtRiskOfOcupationExposureId : personEnrolledInPepPRogramAtRiskOfOcupationExposureIds) {
            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                if (personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId)) {
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {

                            if ((personEnrolledInPepPRogramAtRiskOfOcupationExposureId.equals(personEnrolledInPepId)
                                    && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                            .equals(patientInProgramId))
                                    && personEnrolledInPepPRogramAtRiskOfOcupationExposureId
                                            .equals(personAtRiskOnPEPId)) {

                                Person person = Context.getPersonService()
                                        .getPerson(personEnrolledInPepPRogramAtRiskOfOcupationExposureId);
                                patients.add(person);
                            }
                        }
                    }
                }
            }
        }
        return patients;

    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivRapeAssault3MonthAfterPep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivRapeAssault3MonthAfterPepList(String startDate, String endDate) {
        ArrayList<Person> persons = new ArrayList<Person>();
        /*
         * Date myDate=null; SimpleDateFormat date=new
         * SimpleDateFormat("yyyy-MM-dd"); try { myDate=date.parse(startDate);
         * 
         * Calendar cal=Calendar.getInstance(); if(myDate!=null)
         * cal.setTime(myDate); cal.add(Calendar.MONTH, -3); Date
         * beforeThreeMonthOfStartDate=cal.getTime();
         */

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId()) + "' ")
                .list();
        List<Integer> personOnArvDrug = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id = "
                        + ConstantValues.PROPHYLAXIS_STARTED
                        + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null ")
                .list();

        for (Integer patientInProgramId : patientInProgramIds) {
            for (Integer personOnArvDrugId : personOnArvDrug) {
                if (patientInProgramId.equals(personOnArvDrugId)) {
                    Person person = Context.getPersonService().getPerson(patientInProgramId);
                    persons.add(person);
                }
            }
        }

        return persons;

    }

    /**
     * Number of new clients at risk of HIV infection as a result of rape/sexual
     * assault who received PEP
     * 
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newAtRiskHivRapeAssaultPep(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newAtRiskHivRapeAssaultPepList(String startDate, String endDate) {
        ArrayList<Person> patients = new ArrayList<Person>();

        Session session = getSessionFactory().getCurrentSession();
        List<Integer> personEnrolledInPepPRogramAtRiskOfRapeAssaultIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN patient pat ON pat.patient_id = pp.patient_id ")
                .list();
        List<Integer> personEnrolledInPepIds = session.createSQLQuery(
                "SELECT DISTINCT pe.person_id from person pe inner join patient pat ON pat.patient_id = pe.person_id ")
                .list();
        List<Integer> personOnEncountersWithIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp inner join encounter enc on pp.patient_id=enc.patient_id")
                .list();
        List<Integer> patientInProgramIds = session.createSQLQuery(
                "SELECT DISTINCT pp.patient_id FROM patient_program pp INNER JOIN program pro ON pro.program_id = pp.program_id where pp.program_id= '"
                        + Integer.parseInt(GlobalProperties.gpGetPEPProgramId())
                        + "' and pp.date_enrolled between '" + startDate + "' AND '" + endDate + "' ")
                .list();
        List<Integer> personAtRiskOnPEPIds = session.createSQLQuery(
                "SELECT DISTINCT p.person_id from person p inner join obs o on p.person_id=o.person_id where p.voided=false and o.concept_id='"
                        + Integer.parseInt(GlobalProperties.gpGetReasonpatientStartedArvsForProphylaxisId())
                        + "' and o.value_coded='" + Integer.parseInt(GlobalProperties.gpGetSexualAssaultId())
                        + "' ")
                .list();
        List<Integer> personOnArvDrug = session.createSQLQuery(
                "SELECT DISTINCT pat.patient_id from patient pat inner join orders ord on pat.patient_id=ord.patient_id where ord.concept_id IN "
                        + ConstantValues.LIST_OF_PROPHYLAXIS_DRUGS
                        + "  AND ord.voided = false AND ord.void_reason is null AND ord.order_reason is null")
                .list();

        for (Integer personEnrolledInPepPRogramAtRiskOfRapeAssaultId : personEnrolledInPepPRogramAtRiskOfRapeAssaultIds) {
            for (Integer personEnrolledInPepId : personEnrolledInPepIds) {
                if (personEnrolledInPepPRogramAtRiskOfRapeAssaultId.equals(personEnrolledInPepId))
                    for (Integer patientInProgramId : patientInProgramIds) {
                        for (Integer personAtRiskOnPEPId : personAtRiskOnPEPIds) {
                            if (patientInProgramId.equals(personAtRiskOnPEPId))
                                for (Integer personOnArvDrugId : personOnArvDrug) {
                                    for (Integer personOnEncountersWithId : personOnEncountersWithIds) {
                                        if ((personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                .equals(personEnrolledInPepId)
                                                && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                        .equals(patientInProgramId))
                                                && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                        .equals(personAtRiskOnPEPId)
                                                && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                        .equals(personOnArvDrugId)
                                                && personEnrolledInPepPRogramAtRiskOfRapeAssaultId
                                                        .equals(personOnEncountersWithId)) {

                                            Person person = Context.getPersonService()
                                                    .getPerson(personEnrolledInPepPRogramAtRiskOfRapeAssaultId);
                                            patients.add(person);
                                        }
                                    }
                                }
                        }
                    }
            }
        }
        return patients;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#newMaleMoreThanFifteenInHivCareList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> newMaleMoreThanFifteenInHivCareList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        // Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        /* try { */

        Session session = getSessionFactory().getCurrentSession();

        SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                + "inner join person pe on pg.patient_id = pe.person_id "
                + "inner join patient pa on pg.patient_id = pa.patient_id "
                + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 14 " + " and pg.voided = 0 and pe.voided = 0 "
                + " and pa.voided = 0 and pe.gender = 'M' and pg.date_enrolled >= '" + startDate
                + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

        List<Integer> patientIds1 = query1.list();

        for (Integer patientId : patientIds1) {

            SQLQuery queryDateEnrolled = session.createSQLQuery(
                    "select cast(min(date_enrolled) as DATE) from patient_program where (select cast((date_enrolled) as DATE)) is not null and patient_id = "
                            + patientId);
            List<Date> dateEnrolled = queryDateEnrolled.list();

            if (dateEnrolled.get(0) != null) {

                if ((dateEnrolled.get(0).getTime() >= newStartDate.getTime())
                        && (dateEnrolled.get(0).getTime() <= newEndDate.getTime()))

                {

                    SQLQuery queryTransferredIn = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                    + " and o.voided = 0 and o.person_id= " + patientId);

                    List<Integer> patientIds4 = queryTransferredIn.list();

                    if (patientIds4.size() == 0) {
                        patientIdsList.add(patientId);

                    }
                }
            }
        }

        for (Integer patientId : patientIdsList) {
            patients.add(Context.getPersonService().getPerson(patientId));
        }

        // }

        /*
         * catch (Exception e) {
         * 
         * e.printStackTrace();
         */
        // }
        return patients;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PedsUnderFifteenEnrolledInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int PedsUnderFifteenEnrolledInHiv(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#AdultMoreThanFifteenEnrolledInHiv(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int AdultMoreThanFifteenEnrolledInHiv(String startDate, String endDate) throws ParseException {
        int indicator = 0;

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    indicator++;

                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#AdultMoreThanFifteenEnrolledInHivList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> AdultMoreThanFifteenEnrolledInHivList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        //SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        // Date newEndDate = df.parse(endDate);

        // Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PedsUnderFifteenEnrolledInHivList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> PedsUnderFifteenEnrolledInHivList(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                    + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                    + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                    + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id " + "where ord.concept_id IN ("
                        + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    patientIdsList.add(patientId);

                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return patients;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVDiedThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int PatientsInPreARVDiedThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                    + " and ord.date_stopped is not null and ord.order_reason = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and value_coded= "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfDeath = queryDate.list();

                    if (dateOfDeath.size() != 0)
                        if ((dateOfDeath.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDeath.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVDiedThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> PatientsInPreARVDiedThisMonthList(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                    + " and ord.date_stopped is not null and ord.order_reason = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId()) + " and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and value_coded= "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareDiedConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfDeath = queryDate.list();

                    if (dateOfDeath.size() != 0)
                        if ((dateOfDeath.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfDeath.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);

                        }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTLostToFollowUpThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int PatientsInPreARVTLostToFollowUpThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryDate1 = session
                                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                        + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                        + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                        + patientId);

                        List<Date> maxEnocunterDateTime = queryDate1.list();

                        SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + endDate
                                + "' and concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                + patientId);

                        List<Date> maxReturnVisitDay = queryDate2.list();

                        if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                    || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                            && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            }

                            else {
                                indicator++;
                            }
                        }

                        else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            }

                            else {
                                indicator++;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTLostToFollowUpThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> PatientsInPreARVTLostToFollowUpThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryDate1 = session
                                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                        + "(select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                        + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                        + patientId);

                        List<Date> maxEnocunterDateTime = queryDate1.list();

                        SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + endDate
                                + "' and concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                + patientId);

                        List<Date> maxReturnVisitDay = queryDate2.list();

                        if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())
                                    || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                            && (maxReturnVisitDay.get(0).getTime()) <= newEndDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            }

                            else {
                                patientIdsList.add(patientId);

                            }
                        }

                        else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeEndDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) <= newEndDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            }

                            else {
                                patientIdsList.add(patientId);

                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTransferredInThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int PatientsInPreARVTransferredInThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetYesAsAnswerToTransferredInConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query2Date = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIds3 = query2Date.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateTransferredIn = queryDate.list();

                        if (dateTransferredIn.size() != 0)
                            if ((dateTransferredIn.get(0).getTime() >= newStartDate.getTime())
                                    && (dateTransferredIn.get(0).getTime() <= newEndDate.getTime())) {

                                indicator++;
                            }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTransferredInThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings({ "unchecked" })
    @Override
    public List<Person> PatientsInPreARVTransferredInThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetYesAsAnswerToTransferredInConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query2Date = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIds3 = query2Date.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryDate = session
                                .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetTransferredInConceptId())
                                        + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                        + patientId);

                        List<Date> dateTransferredIn = queryDate.list();

                        if (dateTransferredIn.size() != 0)
                            if ((dateTransferredIn.get(0).getTime() >= newStartDate.getTime())
                                    && (dateTransferredIn.get(0).getTime() <= newEndDate.getTime())) {

                                patientIdsList.add(patientId);
                            }
                    }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTransferredOutThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings({ "unchecked" })
    @Override
    public int PatientsInPreARVTransferredOutThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and value_coded= "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfTransferredOut = queryDate.list();

                    if (dateOfTransferredOut.size() != 0)
                        if ((dateOfTransferredOut.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfTransferredOut.get(0).getTime() <= newEndDate.getTime())) {

                            indicator++;
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTransferredOutThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> PatientsInPreARVTransferredOutThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join obs o on pg.patient_id = o.person_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and o.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate
                    + "' and pg.date_enrolled <= '" + endDate + "' and o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId()) + " and o.value_coded = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                    + " and pg.program_id =  " + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryDate = session
                            .createSQLQuery("select cast(obs_datetime as DATE) from obs where concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and value_coded= "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromTransferredOutConceptId())
                                    + " and (select cast(obs_datetime as DATE)) is not null and voided = 0 and person_id = "
                                    + patientId);

                    List<Date> dateOfTransferredOut = queryDate.list();

                    if (dateOfTransferredOut.size() != 0)
                        if ((dateOfTransferredOut.get(0).getTime() >= newStartDate.getTime())
                                && (dateOfTransferredOut.get(0).getTime() <= newEndDate.getTime())) {

                            patientIdsList.add(patientId);
                        }
                }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInARVTLostToFollowUpNotLostThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int PatientsInARVTLostToFollowUpNotLostThisMonth(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        List<Integer> patientIdsListNotLostToFollowUp = new ArrayList<Integer>();

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newStartDate = df.parse(startDate);

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeStartDate = df.parse(addDaysToDate(startDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) < '" + startDate
                    + "' and pg.date_enrolled < '" + startDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) < '" + startDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate1 = session
                            .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                    + "(select(cast(max(encounter_datetime)as Date))) <= '" + startDate
                                    + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                    + patientId);

                    List<Date> maxEnocunterDateTime = queryDate1.list();

                    SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + startDate
                            + "' and concept_id = "
                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                            + patientId);

                    List<Date> maxReturnVisitDay = queryDate2.list();

                    if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())
                                || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                        && (maxReturnVisitDay.get(0).getTime()) < newStartDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {

                            patientIdsListNotLostToFollowUp.add(patientId);
                        }
                    }

                    else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        } else {

                            patientIdsListNotLostToFollowUp.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsListNotLostToFollowUp) {

                SQLQuery queryDate4 = session
                        .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                + "(select(cast(max(encounter_datetime)as Date))) >= '" + startDate
                                + "' and (select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                + patientId);

                List<Date> maxEnocunterDateTimeBetweenStartAndEndDate = queryDate4.list();

                if (maxEnocunterDateTimeBetweenStartAndEndDate.size() != 0)

                    if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0) != null)

                    {

                        if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() >= newStartDate.getTime()
                                && maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() <= newEndDate
                                        .getTime()) {

                            indicator++;
                        }
                    }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInARVTLostToFollowUpNotLostThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> PatientsInARVTLostToFollowUpNotLostThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        List<Integer> patientIdsListNotLostToFollowUp = new ArrayList<Integer>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newStartDate = df.parse(startDate);

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeStartDate = df.parse(addDaysToDate(startDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) < '" + startDate
                    + "' and pg.date_enrolled < '" + startDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery queryExited = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (cast(o.obs_datetime as DATE)) < '" + startDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds3 = queryExited.list();

                if (patientIds3.size() == 0) {

                    SQLQuery queryDate1 = session
                            .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                    + "(select(cast(max(encounter_datetime)as Date))) <= '" + startDate
                                    + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                    + patientId);

                    List<Date> maxEnocunterDateTime = queryDate1.list();

                    SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                            + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + startDate
                            + "' and concept_id = "
                            + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                            + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                            + patientId);

                    List<Date> maxReturnVisitDay = queryDate2.list();

                    if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())
                                || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                        && (maxReturnVisitDay.get(0).getTime()) < newStartDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        }

                        else {

                            patientIdsListNotLostToFollowUp.add(patientId);
                        }
                    }

                    else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                        if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())) {

                            patientsNotLostToFollowUp.add(patientId);

                        } else {

                            patientIdsListNotLostToFollowUp.add(patientId);

                        }
                    }
                }
            }

            for (Integer patientId : patientIdsListNotLostToFollowUp) {

                SQLQuery queryDate4 = session
                        .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                + "(select(cast(max(encounter_datetime)as Date))) >= '" + startDate
                                + "' and (select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                + patientId);

                List<Date> maxEnocunterDateTimeBetweenStartAndEndDate = queryDate4.list();

                if (maxEnocunterDateTimeBetweenStartAndEndDate.size() != 0)

                    if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0) != null)

                    {

                        if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() >= newStartDate.getTime()
                                && maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() <= newEndDate
                                        .getTime()) {

                            patientIdsList.add(patientId);
                        }
                    }
            }
            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTLostToFollowUpNotLostThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int PatientsInPreARVTLostToFollowUpNotLostThisMonth(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        List<Integer> patientIdsListNotLostToFollowUp = new ArrayList<Integer>();

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newStartDate = df.parse(startDate);

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeStartDate = df.parse(addDaysToDate(startDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) < '" + startDate
                    + "' and pg.date_enrolled < '" + startDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) < '" + startDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) < '" + startDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryDate1 = session
                                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                        + "(select(cast(max(encounter_datetime)as Date))) <= '" + startDate
                                        + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                        + patientId);

                        List<Date> maxEnocunterDateTime = queryDate1.list();

                        SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + startDate
                                + "' and concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                + patientId);

                        List<Date> maxReturnVisitDay = queryDate2.list();

                        if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())
                                    || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                            && (maxReturnVisitDay.get(0).getTime()) < newStartDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            }

                            else {

                                patientIdsListNotLostToFollowUp.add(patientId);
                            }
                        }

                        else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            } else {

                                patientIdsListNotLostToFollowUp.add(patientId);

                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsListNotLostToFollowUp) {

                // SQLQuery queryARV = session
                // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                // + "inner join person pe on pg.patient_id = pe.person_id "
                // + "inner join patient pa on pg.patient_id = pa.patient_id "
                // + "inner join orders ord on pg.patient_id = ord.patient_id "
                // + "inner join drug_order do on ord.order_id = do.order_id "
                // + "inner join drug d on do.drug_inventory_id = d.drug_id "
                // + "where d.concept_id IN ("
                // + GlobalProperties.gpGetListOfARVsDrugs()
                // +
                // ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                // + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '"
                // + startDate
                // + "'and (cast(ord.date_activated as DATE)) <= '"
                // + endDate
                // + "' and pg.date_enrolled <= '"
                // + endDate
                // + "' and pg.date_completed is null and pg.patient_id = "
                // + patientId
                // + " and pg.program_id =  "
                // + Integer.parseInt(GlobalProperties
                // .gpGetHIVProgramId()));
                //
                // List<Integer> patientIdsARV = queryARV.list();
                //
                // if (patientIdsARV.size() == 0) {

                SQLQuery queryDate4 = session
                        .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                + "(select(cast(max(encounter_datetime)as Date))) >= '" + startDate
                                + "' and (select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                + patientId);

                List<Date> maxEnocunterDateTimeBetweenStartAndEndDate = queryDate4.list();

                if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0) != null) {
                    if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() >= newStartDate.getTime()
                            && maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() <= newEndDate
                                    .getTime()) {

                        indicator++;
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;

    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#PatientsInPreARVTLostToFollowUpNotLostThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> PatientsInPreARVTLostToFollowUpNotLostThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        List<Integer> patientIdsListNotLostToFollowUp = new ArrayList<Integer>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newStartDate = df.parse(startDate);

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeStartDate = df.parse(addDaysToDate(startDate, -3));

        ArrayList<Integer> patientsNotLostToFollowUp = new ArrayList<Integer>();

        Session session = getSessionFactory().getCurrentSession();

        try {

            SQLQuery query1 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                    + "inner join person pe on pg.patient_id = pe.person_id "
                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                    + "inner join orders ord on pg.patient_id = ord.patient_id "
                    + "inner join drug_order do on ord.order_id = do.order_id "
                    /*
                     * +
                     * "inner join drug d on do.drug_inventory_id = d.drug_id "
                     */
                    + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfProphylaxisDrugs()
                    + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                    + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) < '" + startDate
                    + "' and pg.date_enrolled < '" + startDate + "' and pg.program_id =  "
                    + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIds1 = query1.list();

            for (Integer patientId : patientIds1) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) < '" + startDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) < '" + startDate
                                    + "' and o.voided = 0 and o.person_id=" + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        SQLQuery queryDate1 = session
                                .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                        + "(select(cast(max(encounter_datetime)as Date))) <= '" + startDate
                                        + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                        + patientId);

                        List<Date> maxEnocunterDateTime = queryDate1.list();

                        SQLQuery queryDate2 = session.createSQLQuery("select cast(max(value_datetime) as DATE ) "
                                + "from obs where (select(cast(max(value_datetime)as Date))) <= '" + startDate
                                + "' and concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetReturnVisitDateConceptId())
                                + " and (select cast(max(value_datetime) as DATE )) is not null and voided = 0 and person_id = "
                                + patientId);

                        List<Date> maxReturnVisitDay = queryDate2.list();

                        if (((maxReturnVisitDay.get(0)) != null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())
                                    || ((maxReturnVisitDay.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                            && (maxReturnVisitDay.get(0).getTime()) < newStartDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            }

                            else {

                                patientIdsListNotLostToFollowUp.add(patientId);
                            }
                        }

                        else if (((maxReturnVisitDay.get(0)) == null) && (maxEnocunterDateTime.get(0) != null)) {

                            if (((maxEnocunterDateTime.get(0).getTime()) >= threeMonthsBeforeStartDate.getTime()
                                    && (maxEnocunterDateTime.get(0).getTime()) < newStartDate.getTime())) {

                                patientsNotLostToFollowUp.add(patientId);

                            } else {

                                patientIdsListNotLostToFollowUp.add(patientId);

                            }
                        }
                    }
                }
            }
            for (Integer patientId : patientIdsListNotLostToFollowUp) {

                // SQLQuery queryARV = session
                // .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                // + "inner join person pe on pg.patient_id = pe.person_id "
                // + "inner join patient pa on pg.patient_id = pa.patient_id "
                // + "inner join orders ord on pg.patient_id = ord.patient_id "
                // + "inner join drug_order do on ord.order_id = do.order_id "
                // + "inner join drug d on do.drug_inventory_id = d.drug_id "
                // + "where d.concept_id IN ("
                // + GlobalProperties.gpGetListOfARVsDrugs()
                // +
                // ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                // + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '"
                // + startDate
                // + "'and (cast(ord.date_activated as DATE)) <= '"
                // + endDate
                // + "' and pg.date_enrolled <= '"
                // + endDate
                // + "' and pg.date_completed is null and pg.patient_id = "
                // + patientId
                // + " and pg.program_id =  "
                // + Integer.parseInt(GlobalProperties
                // .gpGetHIVProgramId()));
                //
                // List<Integer> patientIdsARV = queryARV.list();
                //
                // if (patientIdsARV.size() == 0) {

                SQLQuery queryDate4 = session
                        .createSQLQuery("select cast(max(encounter_datetime)as DATE) from encounter where "
                                + "(select(cast(max(encounter_datetime)as Date))) >= '" + startDate
                                + "' and (select(cast(max(encounter_datetime)as Date))) <= '" + endDate
                                + "' and (select cast(max(encounter_datetime)as DATE)) is not null and voided = 0 and patient_id = "
                                + patientId);

                List<Date> maxEnocunterDateTimeBetweenStartAndEndDate = queryDate4.list();

                if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0) != null) {
                    if (maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() >= newStartDate.getTime()
                            && maxEnocunterDateTimeBetweenStartAndEndDate.get(0).getTime() <= newEndDate
                                    .getTime()) {

                        patientIdsList.add(patientId);
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosStartedCotrimoxazoleThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int pregnantHivPosStartedCotrimoxazoleThisMonth(String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        /* try { */

        Session session = getSessionFactory().getCurrentSession();
        SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                + "inner join obs ob on pg.patient_id = ob.person_id "
                + "inner join person pe on pg.patient_id = pe.person_id "
                + "inner join patient pa on pg.patient_id = pa.patient_id "
                + "inner join encounter enc on pg.patient_id = enc.patient_id "
                + "where pe.gender = 'f' and pg.program_id = "
                + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 ");

        // Getting the size of the returned LIST which equals to the COUNTS
        // needed
        List<Integer> patientIds = query.list();

        for (Integer patientId : patientIds) {

            SQLQuery query2 = session.createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                    + " and o.voided = 0 and o.person_id=" + patientId);

            List<Integer> patientIds2 = query2.list();

            if (patientIds2.size() == 0) {

                SQLQuery queryHIVResultDate = session
                        .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                + " and o.value_coded in (" + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                + patientId);
                List<Date> HivTestResultDate = queryHIVResultDate.list();

                if (HivTestResultDate.size() != 0)

                {

                    SQLQuery queryHIVResultConcept = session
                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and o.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '" + HivTestResultDate
                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                    if (HivTestResultConcept.size() != 0) {

                        if (HivTestResultConcept.get(0) == Integer
                                .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                            SQLQuery queryMinStartDate = session
                                    .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                            + " inner join drug_order do on ord.order_id = do.order_id "

                                            + " where ord.concept_id IN ("
                                            + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                                            + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                            + patientId);

                            List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                            if (patientIdsMinStartDate.size() != 0) {

                                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                                    indicator++;
                                }

                            }
                        }
                    }
                }
            }
        }
        /*
         * } catch (Exception e) { e.printStackTrace(); }
         */

        return indicator;
    }

    /**
     * @throws ParseException
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#pregnantHivPosStartedCotrimoxazoleThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> pregnantHivPosStartedCotrimoxazoleThisMonthList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        /* try { */

        Session session = getSessionFactory().getCurrentSession();
        SQLQuery query = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                + "inner join obs ob on pg.patient_id = ob.person_id "
                + "inner join person pe on pg.patient_id = pe.person_id "
                + "inner join patient pa on pg.patient_id = pa.patient_id "
                + "inner join encounter enc on pg.patient_id = enc.patient_id "
                + "where pe.gender = 'f' and pg.program_id = "
                + Integer.parseInt(GlobalProperties.gpGetPMTCTProgramId())
                + " and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 and enc.voided=0 ");

        // Getting the size of the returned LIST which equals to the COUNTS
        // needed
        List<Integer> patientIds = query.list();

        for (Integer patientId : patientIds) {

            SQLQuery query2 = session.createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                    + " and o.voided = 0 and o.person_id=" + patientId);

            List<Integer> patientIds2 = query2.list();

            if (patientIds2.size() == 0) {

                SQLQuery queryHIVResultDate = session
                        .createSQLQuery("select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                + " and o.value_coded in (" + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                + patientId);
                List<Date> HivTestResultDate = queryHIVResultDate.list();

                if (HivTestResultDate.size() != 0)

                {

                    SQLQuery queryHIVResultConcept = session
                            .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and o.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                    + HivTestResultDate.get(0)
                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                    + patientId);
                    List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                    if (HivTestResultConcept.size() != 0) {

                        if (HivTestResultConcept.get(0) == Integer
                                .parseInt(GlobalProperties.gpGetPositiveAsResultToHIVTestConceptId())) {

                            SQLQuery queryMinStartDate = session
                                    .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                            + " inner join drug_order do on ord.order_id = do.order_id "
                                            + " inner join drug d on do.drug_inventory_id = d.drug_id "
                                            + " where d.concept_id IN ("
                                            + GlobalProperties.gpGetListOfProphylaxisDrugs() + ") "
                                            + " and (select (cast(min(ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                            + patientId);

                            List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                            if (patientIdsMinStartDate.size() != 0) {
                                if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                                        && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                                    patientIdsList.add(patientId);
                                }

                            }
                        }
                    }
                }
            }
        }
        for (Integer patientId : patientIdsList) {
            patients.add(Context.getPersonService().getPerson(patientId));
        }
        /*
         * } catch (Exception e) { e.printStackTrace(); }
         */

        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivNegMothersInDiscordantCouplesEnrolledPmtct(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public int infantHivNegMothersInDiscordantCouplesEnrolledPmtct(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub
        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id= "
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + "inner join person pe on rel.person_b = pe.person_id "
                                                                    + "inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + "where rel.person_a = " + patientId
                                                                    + " and pg.program_id = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())

                                                                    + " and pg.voided = 0  and rel.voided = 0 and (cast(pg.date_enrolled as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (cast(pg.date_enrolled as DATE)) <= '"
                                                                    + endDate + "' ");
                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryExposedInfantInPMTCT = session
                                                                        .createSQLQuery(
                                                                                "select (cast(pg.date_enrolled as DATE)) from patient_program pg"
                                                                                        + " where pg.patient_id = "
                                                                                        + patientIdsInfant
                                                                                        + " and (select (cast(pg.date_enrolled as DATE))) is not null and pg.voided = 0 and pg.program_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId()));

                                                                List<Date> exposedInfantInPMTCT = queryExposedInfantInPMTCT
                                                                        .list();

                                                                if ((exposedInfantInPMTCT.get(0)
                                                                        .getTime() >= newStartDate.getTime())
                                                                        && (exposedInfantInPMTCT.get(0)
                                                                                .getTime() <= newEndDate
                                                                                        .getTime())) {

                                                                    indicator++;

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return indicator;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#infantHivNegMothersInDiscordantCouplesEnrolledPmtctList(java.lang.String,
     *      java.lang.String)
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Person> infantHivNegMothersInDiscordantCouplesEnrolledPmtctList(String startDate, String endDate)
            throws ParseException {
        // TODO Auto-generated method stub

        ArrayList<Person> patients = new ArrayList<Person>();

        List<Integer> patientIdsList = new ArrayList<Integer>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();
            SQLQuery query = session.createSQLQuery("select distinct rel.person_a from relationship rel "
                    + "inner join person pe on rel.person_a = pe.person_id " + "where pe.gender = 'f' "
                    + " and rel.voided = 0 and pe.voided = 0 ");

            // Getting the size of the returned LIST which equals to the COUNTS
            // needed
            List<Integer> patientIds = query.list();

            for (Integer patientId : patientIds) {

                SQLQuery query2 = session
                        .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                + " and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                + "' and o.voided = 0 and o.person_id=" + patientId);

                List<Integer> patientIds2 = query2.list();

                if (patientIds2.size() == 0) {

                    SQLQuery query3 = session
                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                    + "where ob.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                    + "' and ob.value_coded in ("
                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                    + " and pg.patient_id = " + patientId);

                    List<Integer> patientIds3 = query3.list();

                    if (patientIds3.size() != 0) {
                        SQLQuery queryHIVResultDate = session.createSQLQuery(
                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                        + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                        + " and o.value_coded in ("
                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '" + endDate
                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                        + patientId);
                        List<Date> HivTestResultDate = queryHIVResultDate.list();

                        if (HivTestResultDate.size() != 0) {

                            SQLQuery queryHIVResultConcept = session
                                    .createSQLQuery("select o.value_coded from obs o where o.concept_id = "
                                            + Integer.parseInt(GlobalProperties.gpGetResultForHIVTestConceptId())
                                            + " and o.value_coded in ("
                                            + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                            + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                            + HivTestResultDate.get(0)
                                            + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                            + patientId);
                            List<Integer> HivTestResultConcept = queryHIVResultConcept.list();

                            if (HivTestResultConcept.size() != 0) {

                                if (HivTestResultConcept.get(0) == Integer
                                        .parseInt(GlobalProperties.gpGetNegativeAsResultToHIVTestConceptId())) {

                                    SQLQuery queryTestingStatusOfPartner = session
                                            .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                                                    + "inner join obs ob on pg.patient_id = ob.person_id "
                                                    + "inner join person pe on pg.patient_id = pe.person_id "
                                                    + "inner join patient pa on pg.patient_id = pa.patient_id "
                                                    + "where ob.concept_id = "
                                                    + Integer.parseInt(
                                                            GlobalProperties.gpGetTestingStatusOfPartnerConceptId())
                                                    + " and (cast(ob.obs_datetime as DATE)) <= '" + endDate
                                                    + "' and ob.value_coded in ("
                                                    + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                    + ") and (cast(pg.date_enrolled as DATE)) <= '" + endDate
                                                    + "' and pg.voided = 0 and ob.voided = 0 and pe.voided = 0 and pa.voided = 0 "
                                                    + " and pg.patient_id = " + patientId);

                                    List<Integer> patientIdsTestingStatusOfPartner = queryTestingStatusOfPartner
                                            .list();

                                    if (patientIdsTestingStatusOfPartner.size() != 0) {

                                        SQLQuery queryHIVResultDateTestingStatusOfPartner = session.createSQLQuery(
                                                "select cast(max(o.obs_datetime)as DATE) from obs o where o.concept_id = "
                                                        + Integer.parseInt(GlobalProperties
                                                                .gpGetTestingStatusOfPartnerConceptId())
                                                        + " and o.value_coded in ("
                                                        + GlobalProperties.gpGetListOfAnswersToResultOfHIVTest()
                                                        + ") and (select cast(max(o.obs_datetime)as DATE)) <= '"
                                                        + endDate
                                                        + "' and (select cast(max(o.obs_datetime)as DATE)) is not null and o.voided = 0 and o.person_id="
                                                        + patientId);
                                        List<Date> HivTestResultDateHIVResultDateTestingStatusOfPartner = queryHIVResultDateTestingStatusOfPartner
                                                .list();

                                        if (HivTestResultDateHIVResultDateTestingStatusOfPartner.size() != 0) {

                                            SQLQuery queryHIVResultConceptTestingStatusOfPartner = session
                                                    .createSQLQuery(
                                                            "select o.value_coded from obs o where o.concept_id = "
                                                                    + Integer.parseInt(GlobalProperties
                                                                            .gpGetTestingStatusOfPartnerConceptId())
                                                                    + " and o.value_coded in ("
                                                                    + GlobalProperties
                                                                            .gpGetListOfAnswersToResultOfHIVTest()
                                                                    + ") and (select cast(max(o.obs_datetime)as DATE)) = '"
                                                                    + HivTestResultDate.get(0)
                                                                    + "' and o.value_coded is not null and o.voided = 0 and o.person_id= "
                                                                    + patientId);
                                            List<Integer> HivTestResultConceptHIVResultConceptTestingStatusOfPartner = queryHIVResultConceptTestingStatusOfPartner
                                                    .list();

                                            if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                    .size() != 0) {

                                                if (HivTestResultConceptHIVResultConceptTestingStatusOfPartner
                                                        .get(0) == Integer.parseInt(GlobalProperties
                                                                .gpGetPositiveAsResultToHIVTestConceptId())) {

                                                    SQLQuery infantHIVPositiveInPMTCT = session.createSQLQuery(
                                                            "select distinct rel.person_b from relationship rel "
                                                                    + "inner join person pe on rel.person_b = pe.person_id "
                                                                    + "inner join patient_program pg on rel.person_b = pg.patient_id "
                                                                    + "where rel.person_a = " + patientId
                                                                    + " and pg.program_id = "
                                                                    + Integer.parseInt(
                                                                            GlobalProperties.gpGetPMTCTProgramId())

                                                                    + " and pg.voided = 0  and rel.voided = 0 and (cast(pg.date_enrolled as DATE)) >= '"
                                                                    + startDate
                                                                    + "' and (cast(pg.date_enrolled as DATE)) <= '"
                                                                    + endDate + "' ");
                                                    List<Integer> infantHIVPositive = infantHIVPositiveInPMTCT
                                                            .list();

                                                    if (infantHIVPositive.size() != 0) {

                                                        for (Integer patientIdsInfant : infantHIVPositive) {

                                                            SQLQuery queryInfantExited = session.createSQLQuery(
                                                                    "select distinct o.person_id from obs o where o.concept_id = "
                                                                            + Integer.parseInt(GlobalProperties
                                                                                    .gpGetExitFromCareConceptId())
                                                                            + " and o.voided = 0 and o.person_id="
                                                                            + patientIdsInfant);

                                                            List<Integer> patientIds2InfantExited = queryInfantExited
                                                                    .list();

                                                            if (patientIds2InfantExited.size() == 0) {

                                                                SQLQuery queryExposedInfantInPMTCT = session
                                                                        .createSQLQuery(
                                                                                "select (cast(pg.date_enrolled as DATE)) from patient_program pg"
                                                                                        + " where pg.patient_id = "
                                                                                        + patientIdsInfant
                                                                                        + " and (select (cast(pg.date_enrolled as DATE))) is not null and pg.voided = 0 and pg.program_id = "
                                                                                        + Integer.parseInt(
                                                                                                GlobalProperties
                                                                                                        .gpGetPMTCTProgramId()));

                                                                List<Date> exposedInfantInPMTCT = queryExposedInfantInPMTCT
                                                                        .list();

                                                                if ((exposedInfantInPMTCT.get(0)
                                                                        .getTime() >= newStartDate.getTime())
                                                                        && (exposedInfantInPMTCT.get(0)
                                                                                .getTime() <= newEndDate
                                                                                        .getTime())) {

                                                                    patientIdsList.add(patientIdsInfant);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                        }

                                    }
                                }
                            }
                        }
                    }
                }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }

        } catch (Exception e) {
            e.printStackTrace();

        }

        return patients;

    }

    public int patientsOnCotrimoProphylaxisLessThan15Years(String startDate, String endDate) throws ParseException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * "inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 15 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfProphylaxisDrugs()
                            + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + "and pa.voided = 0 and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds1 = query2.list();

                // for (Integer patientId : patientIds1) {

                if (patientIds1.size() == 0) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                    + " and o.voided = 0 and o.person_id= " + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        /*
                         * SQLQuery queryDate1 = session.createSQLQuery(
                         * "select cast(max(encounter_datetime)as DATE) from encounter where "
                         * +
                         * "(select(cast(max(encounter_datetime)as Date))) <= '"
                         * + endDate +
                         * "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                         * + patientId);
                         * 
                         * List<Date> maxEnocunterDateTime = queryDate1.list();
                         * 
                         * SQLQuery queryDate2 = session.createSQLQuery(
                         * "select cast(max(value_datetime) as DATE ) " +
                         * "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                         * + endDate + "' and concept_id = " + Integer
                         * .parseInt(GlobalProperties
                         * .gpGetReturnVisitDateConceptId()) +
                         * " and (select(cast(max(value_datetime)as DATE))) is not null and voided = 0 and person_id = "
                         * + patientId);
                         * 
                         * List<Date> maxReturnVisitDay = queryDate2.list();
                         * 
                         * if (((maxReturnVisitDay.get(0)) != null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if (((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0) .getTime()) <=
                         * newEndDate.getTime()) ||
                         * ((maxReturnVisitDay.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxReturnVisitDay .get(0).getTime()) <= newEndDate
                         * .getTime())) {
                         * 
                         * indicator++;
                         * 
                         * } }
                         * 
                         * else if (((maxReturnVisitDay.get(0)) == null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if ((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                         * .getTime()) {
                         * 
                         * indicator++;
                         * 
                         * } } else if (((maxReturnVisitDay.get(0) != null)) &&
                         * (maxReturnVisitDay.get(0).getTime() > newEndDate
                         * .getTime()))
                         * 
                         * {
                         */
                        indicator++;

                    }
                }
            }
        }
        // }

        catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    public List<Person> patientsOnCotrimoProphylaxisLessThan15YearsList(String startDate, String endDate)
            throws ParseException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * "inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 < 15 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfProphylaxisDrugs()
                            + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + "and pa.voided = 0 and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds1 = query2.list();

                // for (Integer patientId : patientIds1) {

                if (patientIds1.size() == 0) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                    + " and o.voided = 0 and o.person_id= " + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        /*
                         * SQLQuery queryDate1 = session.createSQLQuery(
                         * "select cast(max(encounter_datetime)as DATE) from encounter where "
                         * +
                         * "(select(cast(max(encounter_datetime)as Date))) <= '"
                         * + endDate +
                         * "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                         * + patientId);
                         * 
                         * List<Date> maxEnocunterDateTime = queryDate1.list();
                         * 
                         * SQLQuery queryDate2 = session.createSQLQuery(
                         * "select cast(max(value_datetime) as DATE ) " +
                         * "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                         * + endDate + "' and concept_id = " + Integer
                         * .parseInt(GlobalProperties
                         * .gpGetReturnVisitDateConceptId()) +
                         * " and (select(cast(max(value_datetime)as DATE))) is not null and voided = 0 and person_id = "
                         * + patientId);
                         * 
                         * List<Date> maxReturnVisitDay = queryDate2.list();
                         * 
                         * if (((maxReturnVisitDay.get(0)) != null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if (((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0) .getTime()) <=
                         * newEndDate.getTime()) ||
                         * ((maxReturnVisitDay.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxReturnVisitDay .get(0).getTime()) <= newEndDate
                         * .getTime())) {
                         * 
                         * patientIdsList.add(patientId);
                         * 
                         * } }
                         * 
                         * else if (((maxReturnVisitDay.get(0)) == null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if ((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                         * .getTime()) {
                         * 
                         * patientIdsList.add(patientId);
                         * 
                         * } } else if (((maxReturnVisitDay.get(0) != null)) &&
                         * (maxReturnVisitDay.get(0).getTime() > newEndDate
                         * .getTime()))
                         * 
                         * {
                         */
                        patientIdsList.add(patientId);

                    }
                }
            }
            // }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    public int patientsOnCotrimoProphylaxisGreatherThan15Years(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * "inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 14 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfProphylaxisDrugs()
                            + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + "and pa.voided = 0 and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds1 = query2.list();

                if (patientIds1.size() == 0) {

                    // for (Integer patientId : patientIds1) {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                    + " and o.voided = 0 and o.person_id= " + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        /*
                         * SQLQuery queryDate1 = session.createSQLQuery(
                         * "select cast(max(encounter_datetime)as DATE) from encounter where "
                         * +
                         * "(select(cast(max(encounter_datetime)as Date))) <= '"
                         * + endDate +
                         * "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                         * + patientId);
                         * 
                         * List<Date> maxEnocunterDateTime = queryDate1.list();
                         * 
                         * SQLQuery queryDate2 = session.createSQLQuery(
                         * "select cast(max(value_datetime) as DATE ) " +
                         * "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                         * + endDate + "' and concept_id = " + Integer
                         * .parseInt(GlobalProperties
                         * .gpGetReturnVisitDateConceptId()) +
                         * " and (select(cast(max(value_datetime)as DATE))) is not null and voided = 0 and person_id = "
                         * + patientId);
                         * 
                         * List<Date> maxReturnVisitDay = queryDate2.list();
                         * 
                         * if (((maxReturnVisitDay.get(0)) != null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if (((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0) .getTime()) <=
                         * newEndDate.getTime()) ||
                         * ((maxReturnVisitDay.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxReturnVisitDay .get(0).getTime()) <= newEndDate
                         * .getTime())) {
                         * 
                         * indicator++;
                         * 
                         * } }
                         * 
                         * else if (((maxReturnVisitDay.get(0)) == null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if ((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                         * .getTime()) {
                         * 
                         * indicator++;
                         * 
                         * } } else if (((maxReturnVisitDay.get(0) != null)) &&
                         * (maxReturnVisitDay.get(0).getTime() > newEndDate
                         * .getTime()))
                         * 
                         * {
                         */
                        indicator++;

                    }
                }
            }
        }
        // }

        catch (Exception e) {

            e.printStackTrace();
        }
        return indicator;
    }

    public List<Person> patientsOnCotrimoProphylaxisGreatherThan15YearsList(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date threeMonthsBeforeEndDate = df.parse(addDaysToDate(endDate, -3));

        Date newStartDate = df.parse(startDate);

        try {

            Session session = getSessionFactory().getCurrentSession();

            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "inner join drug_order do on ord.order_id = do.order_id "
                            /*
                             * +
                             * "inner join drug d on do.drug_inventory_id = d.drug_id "
                             */
                            + "WHERE DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 14 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfProphylaxisDrugs()
                            + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + "and pa.voided = 0 and pg.date_enrolled <= '" + endDate + "' and pg.program_id =  "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()));

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery query2 = session.createSQLQuery("select distinct pg.patient_id from patient_program pg "
                        + "inner join person pe on pg.patient_id = pe.person_id "
                        + "inner join patient pa on pg.patient_id = pa.patient_id "
                        + "inner join orders ord on pg.patient_id = ord.patient_id "
                        + "inner join drug_order do on ord.order_id = do.order_id "
                        /*
                         * +
                         * "inner join drug d on do.drug_inventory_id = d.drug_id "
                         */
                        + "where ord.concept_id IN (" + GlobalProperties.gpGetListOfARVsDrugs()
                        + ") and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                        + "and pa.voided = 0 and (cast(ord.date_activated as DATE)) <= '" + endDate + "'"
                        + " and pg.patient_id=" + patientId);

                List<Integer> patientIds1 = query2.list();

                // for (Integer patientId : patientIds1) {

                if (patientIds1.size() == 0)

                {

                    SQLQuery queryExited = session
                            .createSQLQuery("select distinct o.person_id from obs o where o.concept_id = "
                                    + Integer.parseInt(GlobalProperties.gpGetExitFromCareConceptId())
                                    + " and (cast(o.obs_datetime as DATE)) <= '" + endDate + "'"
                                    + " and o.voided = 0 and o.person_id= " + patientId);

                    List<Integer> patientIds3 = queryExited.list();

                    if (patientIds3.size() == 0) {

                        /*
                         * SQLQuery queryDate1 = session.createSQLQuery(
                         * "select cast(max(encounter_datetime)as DATE) from encounter where "
                         * +
                         * "(select(cast(max(encounter_datetime)as Date))) <= '"
                         * + endDate +
                         * "' and (select(cast(max(encounter_datetime)as DATE))) is not null and voided = 0 and patient_id = "
                         * + patientId);
                         * 
                         * List<Date> maxEnocunterDateTime = queryDate1.list();
                         * 
                         * SQLQuery queryDate2 = session.createSQLQuery(
                         * "select cast(max(value_datetime) as DATE ) " +
                         * "from obs where (select(cast(max(value_datetime)as Date))) <= '"
                         * + endDate + "' and concept_id = " + Integer
                         * .parseInt(GlobalProperties
                         * .gpGetReturnVisitDateConceptId()) +
                         * " and (select(cast(max(value_datetime)as DATE))) is not null and voided = 0 and person_id = "
                         * + patientId);
                         * 
                         * List<Date> maxReturnVisitDay = queryDate2.list();
                         * 
                         * if (((maxReturnVisitDay.get(0)) != null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if (((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0) .getTime()) <=
                         * newEndDate.getTime()) ||
                         * ((maxReturnVisitDay.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxReturnVisitDay .get(0).getTime()) <= newEndDate
                         * .getTime())) {
                         * 
                         * patientIdsList.add(patientId);
                         * 
                         * } }
                         * 
                         * else if (((maxReturnVisitDay.get(0)) == null) &&
                         * (maxEnocunterDateTime.get(0) != null)) {
                         * 
                         * if ((maxEnocunterDateTime.get(0).getTime()) >=
                         * threeMonthsBeforeEndDate .getTime() &&
                         * (maxEnocunterDateTime.get(0).getTime()) <= newEndDate
                         * .getTime()) {
                         * 
                         * patientIdsList.add(patientId); } } else if
                         * (((maxReturnVisitDay.get(0) != null)) &&
                         * (maxReturnVisitDay.get(0).getTime() > newEndDate
                         * .getTime()))
                         * 
                         * {
                         */
                        patientIdsList.add(patientId);

                    }
                }
            }
            // }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {

            e.printStackTrace();
        }
        return patients;
    }

    public int patientsPediatricNewOnSecondLineThisMonth(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                            + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 13 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfSecondLineDrugs() + ") "
                            + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                            + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                            + endDate + "' ");

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfSecondLineDrugs()
                                + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        indicator++;
                    }
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    public List<Person> patientsPediatricNewOnSecondLineThisMonthList(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                            + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 <= 14 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfSecondLineDrugs() + ") "
                            + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                            + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                            + endDate + "' ");

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfSecondLineDrugs()
                                + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        patientIdsList.add(patientId);
                    }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return patients;

    }

    public int patientsAdultNewOnSecondLineThisMonth(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        int indicator = 0;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "inner join drug_order do on ord.order_id = do.order_id "
                            + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                            + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 15 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfSecondLineDrugs() + ") "
                            + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                            + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                            + endDate + "' ");

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfSecondLineDrugs()
                                + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        indicator++;
                    }
            }

        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return indicator;

    }

    public List<Person> patientsAdultNewOnSecondLineThisMonthList(String startDate, String endDate)
            throws ParseException, HibernateException, NumberFormatException {

        List<Integer> patientIdsList = new ArrayList<Integer>();

        ArrayList<Person> patients = new ArrayList<Person>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

        Date newEndDate = df.parse(endDate);

        Date newStartDate = df.parse(startDate);

        Session session = getSessionFactory().getCurrentSession();

        try {
            SQLQuery queryPatientsOnCotrimo = session
                    .createSQLQuery("select distinct pg.patient_id from patient_program pg "
                            + "inner join person pe on pg.patient_id = pe.person_id "
                            + "inner join patient pa on pg.patient_id = pa.patient_id "
                            + "inner join orders ord on pg.patient_id = ord.patient_id "
                            + "where ((pg.date_completed is null) or (pg.date_completed > '" + endDate
                            + "')) and DATE_FORMAT(FROM_DAYS(TO_DAYS('" + endDate
                            + "') - TO_DAYS(pe.birthdate)), '%Y')+0 >= 14 " + " and ord.concept_id IN ("
                            + GlobalProperties.gpGetListOfSecondLineDrugs() + ") "
                            + " and pg.voided = 0 and pe.voided = 0 and ord.voided = 0 "
                            + " and pa.voided = 0 and (cast(ord.date_activated as DATE)) >= '" + startDate
                            + "' and (cast(ord.date_activated as DATE)) <= '" + endDate + "' and pg.program_id= "
                            + Integer.parseInt(GlobalProperties.gpGetHIVProgramId()) + " and pg.date_enrolled <= '"
                            + endDate + "' ");

            List<Integer> patientIdsOnCotrimo = queryPatientsOnCotrimo.list();

            for (Integer patientId : patientIdsOnCotrimo) {

                SQLQuery queryMinStartDate = session
                        .createSQLQuery("select (cast(min(ord.date_activated)as Date)) from orders ord "
                                + " where ord.concept_id IN (" + GlobalProperties.gpGetListOfSecondLineDrugs()
                                + ") "
                                + " and (select(cast((ord.date_activated)as Date))) is not null and ord.voided = 0 and ord.patient_id = "
                                + patientId);

                List<Date> patientIdsMinStartDate = queryMinStartDate.list();

                if (patientIdsMinStartDate.get(0) != null)

                    if ((patientIdsMinStartDate.get(0).getTime() >= newStartDate.getTime())
                            && patientIdsMinStartDate.get(0).getTime() <= newEndDate.getTime()) {

                        patientIdsList.add(patientId);
                    }
            }

            for (Integer patientId : patientIdsList) {
                patients.add(Context.getPersonService().getPerson(patientId));
            }
        }

        catch (Exception e) {
            e.printStackTrace();
        }
        return patients;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfPregnantWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int NumberOfPregnantWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonth(String startDate,
            String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfPregnantWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> NumberOfPregnantWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonthList(
            String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfLactatingWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int NumberOfLactatingWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonth(String startDate,
            String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfLactatingWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonthList(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> NumberOfLactatingWomenWhoReceivedTherapeuticOrNutritionalSupplementationThisMonthList(
            String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfHIVPositivePregnantWomenIdentifiedAtMaternityWhoStartedTripleTherapyProphylaxis(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int NumberOfHIVPositivePregnantWomenIdentifiedAtMaternityWhoStartedTripleTherapyProphylaxis(
            String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfHIVPositivePregnantWomenIdentifiedAtMaternityWhoStartedTripleTherapyProphylaxisList(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> NumberOfHIVPositivePregnantWomenIdentifiedAtMaternityWhoStartedTripleTherapyProphylaxisList(
            String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfNewInfantsBornFromHIVPositiveMothersWhoReceivedARTProphylaxisAtBirth(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int NumberOfNewInfantsBornFromHIVPositiveMothersWhoReceivedARTProphylaxisAtBirth(String startDate,
            String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#NumberOfNewInfantsBornFromHIVPositiveMothersWhoReceivedARTProphylaxisAtBirthList(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> NumberOfNewInfantsBornFromHIVPositiveMothersWhoReceivedARTProphylaxisAtBirthList(
            String startDate, String endDate) throws ParseException {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#numberOfHIVPositivePregnantWomenWhoReceivedTripleTherapyAsProphylaxis(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public int numberOfHIVPositivePregnantWomenWhoReceivedTripleTherapyAsProphylaxis(String startDate,
            String endDate) {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
     * @see org.openmrs.module.tracnetreporting.service.TracNetIndicatorService#numberOfHIVPositivePregnantWomenWhoReceivedTripleTherapyAsProphylaxisList(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public List<Person> numberOfHIVPositivePregnantWomenWhoReceivedTripleTherapyAsProphylaxisList(String startDate,
            String endDate) {
        // TODO Auto-generated method stub
        return null;
    }
}