using Ease.Core.DataAccess;
using Ease.Core.Model;
using Ease.Core.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using HRM.BO;
using System.Linq;
using NPOI.POIFS.Storage;
using HRM.BO.Configuration;
using Microsoft.AspNetCore.Server.IIS.Core;
using static iTextSharp.text.pdf.AcroFields;
using System.IO;
using Microsoft.AspNetCore.Http;

namespace HRM.DA
{
    #region Leave Entry Service

    public class LeaveEntryService : ServiceTemplate, ILeaveEntryService
    {
        #region Private functions and declaration

        public LeaveEntryService()
        {
        }

        private void MapObject(LeaveEntry oLeaveEntry, DataReader dr)
        {
            base.SetObjectID(oLeaveEntry, dr.GetInt32("TranId").Value);
            oLeaveEntry.EmpID = dr.GetInt32("EmpId").Value;
            oLeaveEntry.EmpGradeId = dr.GetInt32("EmpGradeId").Value;
            oLeaveEntry.LeaveYearId = dr.GetInt32("LeaveYear").Value;
            oLeaveEntry.AppliedParamId = dr.GetInt32("AppParamId", true, 0);
            oLeaveEntry.AppliedLeaveDate = dr.GetDateTime("AppLeaveDate").Value;
            oLeaveEntry.AppliedFromDate = dr.GetDateTime("AppFromDate").Value;
            oLeaveEntry.AppliedToDate = dr.GetDateTime("AppToDate").Value;
            oLeaveEntry.AppliedTotalDays = dr.GetDouble("AppTotalDays").Value;
            oLeaveEntry.ApprovedParamId = dr.GetInt32("AprParamId", true, 0);
            oLeaveEntry.ApprovedLeaveDate = dr.GetDateTime("AprLeaveDate").Value;
            oLeaveEntry.ApprovedFromDate = dr.GetDateTime("AprFromDate").Value;
            oLeaveEntry.ApprovedToDate = dr.GetDateTime("AprToDate").Value;
            oLeaveEntry.ApprovedTotalDays = dr.GetDouble("AprTotalDays").Value;
            oLeaveEntry.LeaveName = dr.GetString("description", true, string.Empty);
            oLeaveEntry.SalaryMonth = dr.GetDateTime("SalaryMonth") == null
                ? DateTime.MinValue
                : dr.GetDateTime("SalaryMonth").Value;
            oLeaveEntry.LFAAmount = dr.GetDouble("LFAAmount", true, 0);
            oLeaveEntry.LFASmokingAmount = dr.GetDouble("LFASmokingAmount", true, 0);
            oLeaveEntry.ApprovedBy = dr.GetString("ApprovedBy") == null ? 0 : dr.GetInt32("ApprovedBy").Value;
            oLeaveEntry.ResponsiblePersonID = dr.GetString("ResponsiblePersonID") == null
                ? 0
                : dr.GetInt32("ResponsiblePersonID").Value;
            oLeaveEntry.Remarks = dr.GetString("Remarks");
            oLeaveEntry.IsDrafted = dr.GetString("IsDrafted") == null ? 0 : dr.GetInt32("IsDrafted").Value;
            oLeaveEntry.IsHalfday = dr.GetString("IsHalfday") == null ? false : dr.GetBoolean("IsHalfday").Value;
            oLeaveEntry.IsAvailed = dr.GetString("IsAvailed") == null ? 0 : dr.GetInt32("IsAvailed").Value;
            oLeaveEntry.EntryDate = dr.GetDateTime("EntryDate").Value;
            oLeaveEntry.LeaveStatus = (EnumLeaveStatus)dr.GetInt32("LeaveStatus").Value;
            oLeaveEntry.SystemType = (EnumSystemType)dr.GetInt32("SystemType", true, 0);
            //transectional properties
            oLeaveEntry.ErnLeaveRemarks = dr.GetString("ErnLeaveRemarks") == null ? "" : dr.GetString("ErnLeaveRemarks");
            oLeaveEntry.LeaveID = dr.GetString("LeaveID") == null ? 0 : dr.GetInt32("LeaveID").Value;
            oLeaveEntry.AppliedLeaveID =
                dr.GetString("AppliedLeaveID") == null ? 0 : dr.GetInt32("AppliedLeaveID").Value;
            oLeaveEntry.SbuID = dr.GetString("SbuID") == null ? 0 : dr.GetInt32("SbuID").Value;
            oLeaveEntry.DepartmentID = dr.GetString("DepartmentID") == null ? 0 : dr.GetInt32("DepartmentID").Value;
            oLeaveEntry.FunctionID = dr.GetString("FunctionID") == null ? 0 : dr.GetInt32("FunctionID").Value;
            oLeaveEntry.LocationID = dr.GetString("LocationID") == null ? 0 : dr.GetInt32("LocationID").Value;
            oLeaveEntry.DesignationID = dr.GetString("DesignationID") == null ? 0 : dr.GetInt32("DesignationID").Value;
            // avail properties
            oLeaveEntry.AvailRemarks = dr.GetString("AvailRemarks") == null ? "" : dr.GetString("AvailRemarks");
            oLeaveEntry.AvailedBy = dr.GetString("AvailedBy") == null ? 0 : dr.GetInt32("AvailedBy").Value;

            oLeaveEntry.LeaveAgainstDate = dr.GetDateTime("leaveAgainstDate") == null
                ? DateTime.MinValue
                : dr.GetDateTime("leaveAgainstDate").Value;
            oLeaveEntry.ItemId = dr.GetInt32("ItemId", true, 0);
            oLeaveEntry.OtValue = dr.GetDouble("OtValue", true, 0);


            string DayPeriodStrinh = dr.GetString("DayPeriod");
            if(DayPeriodStrinh != string.Empty)
                oLeaveEntry.DayPeriod = dr.GetDouble("DayPeriod", true, 0);

            oLeaveEntry.LeaveDayPeriod = dr.GetString("LeaveDayPeriod", true, string.Empty);
            oLeaveEntry.CompensatoryLeaveFor = dr.GetString("CompensatoryLeaveFor") == null ? EnumCompensatoryLeaveFor.None : (EnumCompensatoryLeaveFor)dr.GetInt32("CompensatoryLeaveFor").Value;
            oLeaveEntry.SelectedHalf = (EnumHalf)dr.GetInt32("SelectedHalf").GetValueOrDefault();
            oLeaveEntry.CompensatoryDate = dr.GetDateTime("CompensatoryDate", true, DateTime.MinValue);

            oLeaveEntry.isLFA = dr.GetString("isLFA") == null ? false : dr.GetBoolean("isLFA").Value;
            //oLeaveEntry.AvailTotalDays = dr.GetDouble("AvailTotalDays").Value ;            
            this.SetObjectState(oLeaveEntry, Ease.Core.ObjectState.Saved);
            //this.SetObjectState(oLeaveEntry, ObjectState.Saved);
        }

        private void MapObject(LeaveEntryDetailsMailSenderReport oLeaveEntryDetailsMailSenderReport, DataReader oReader)
        {
            oLeaveEntryDetailsMailSenderReport.LeaveEntryID = oReader.GetInt32("LeaveEntryID").Value;
            oLeaveEntryDetailsMailSenderReport.EmployeeId = oReader.GetInt32("EMPLOYEEID", 0);
            oLeaveEntryDetailsMailSenderReport.EmployeeNo = oReader.GetString("EMPLOYEENO", string.Empty);
            oLeaveEntryDetailsMailSenderReport.Name = oReader.GetString("NAME", string.Empty);
            oLeaveEntryDetailsMailSenderReport.Designation = oReader.GetString("DESIGNATION", string.Empty);
            oLeaveEntryDetailsMailSenderReport.Department = oReader.GetString("DEPARTMENT", string.Empty);
            oLeaveEntryDetailsMailSenderReport.LeaveStatus = Enum.GetName(typeof(EnumAttendanceType), oReader.GetInt32("LEAVESTATUS", 0));
            oLeaveEntryDetailsMailSenderReport.FromDate = oReader.GetDateTime("APPFROMDATE", DateTime.MinValue);
            oLeaveEntryDetailsMailSenderReport.ToDate = oReader.GetDateTime("APPTODATE", DateTime.MinValue);
            oLeaveEntryDetailsMailSenderReport.AprovedDate = oReader.GetDateTime("APRLEAVEDATE", DateTime.MinValue);
            oLeaveEntryDetailsMailSenderReport.Reason = oReader.GetString("Reason", string.Empty);
            oLeaveEntryDetailsMailSenderReport.LocationName = oReader.GetString("LOCATION", string.Empty);
            oLeaveEntryDetailsMailSenderReport.LeaveName = oReader.GetString("LeaveName", string.Empty);
            this.SetObjectState(oLeaveEntryDetailsMailSenderReport, Ease.Core.ObjectState.Saved);
        }

        //For Single employee Leave Ledger and Upcoming Team Leave Mobile App
        private void MapObject(LeaveLedgerMobile oLeaveLedgerMobile, DataReader oReader)
        {
            oLeaveLedgerMobile.employeeNo = oReader.GetString("employeeNo", true, "") ;
            oLeaveLedgerMobile.employeeName = oReader.GetString("Name", true, "");
            oLeaveLedgerMobile.LeaveName = oReader.GetString("LeaveName", string.Empty);
            oLeaveLedgerMobile.FromDate = oReader.GetDateTime("FromDate", DateTime.MinValue);
            oLeaveLedgerMobile.ToDate = oReader.GetDateTime("ToDate", DateTime.MinValue);
            oLeaveLedgerMobile.TotalDays = oReader.GetDouble("TotalDays").Value;
            oLeaveLedgerMobile.Reason = oReader.GetString("Reason", string.Empty);

            this.SetObjectState(oLeaveLedgerMobile, Ease.Core.ObjectState.Saved);
        }

        protected override T CreateObject<T>(DataReader dr)
        {
            LeaveEntry oLeaveEntry = new LeaveEntry();
            MapObject(oLeaveEntry, dr);
            return oLeaveEntry as T;
        }

        LeaveEntry CreateObject(DataReader dr)
        {
            LeaveEntry oLeaveEntry = new LeaveEntry();
            MapObject(oLeaveEntry, dr);
            return oLeaveEntry;
        }

        protected LeaveEntryDetailsMailSenderReport CreateObjectForSchedular(DataReader oReader)
        {
            LeaveEntryDetailsMailSenderReport oLeaveEntryDetailsMailSenderReport = new LeaveEntryDetailsMailSenderReport();
            MapObject(oLeaveEntryDetailsMailSenderReport, oReader);
            return oLeaveEntryDetailsMailSenderReport;
        }

        //For Single employee Leave Ledger Mobile App
        protected LeaveLedgerMobile CreateObjectForLeaveLedgerMobile(DataReader oReader)
        {
            LeaveLedgerMobile oLeaveLedgerMobile = new LeaveLedgerMobile();
            MapObject(oLeaveLedgerMobile, oReader);
            return oLeaveLedgerMobile;
        }

        #endregion

        private void MapObjectForSum(LeaveEntry oLeaveEntry, DataReader dr)
        {
            oLeaveEntry.LeaveYearId = dr.GetInt32("LeaveYear").Value;
            oLeaveEntry.LeaveID =
                dr.GetString("LeaveID") == null ? 0 : dr.GetInt32("LeaveID").Value; //dr.GetInt32("LeaveID").Value;
            oLeaveEntry.EmpID = dr.GetInt32("EmpId").Value;

            oLeaveEntry.ApprovedTotalDays = dr.GetDouble("AprTotalDays").Value;
            oLeaveEntry.LeaveStatus = (EnumLeaveStatus)dr.GetInt32("LeaveStatus").Value;
            this.SetObjectState(oLeaveEntry, Ease.Core.ObjectState.Saved);
        }

        private List<LeaveEntry> CreateObjectForSums(DataReader dr)
        {
            List<LeaveEntry> sumItems = new List<LeaveEntry>();
            while (dr.Read())
            {
                sumItems.Add(CreateObjectForSum(dr));
            }

            return sumItems;
        }

        private LeaveEntry CreateObjectForSum(DataReader dr)
        {
            LeaveEntry oLeaveEntry = new LeaveEntry();
            MapObjectForSum(oLeaveEntry, dr);
            return oLeaveEntry;
        }

        private void MapLeaveAttachmentObject(LeaveAttachment leaveAttachment, DataReader dr)
        {
            base.SetObjectID(leaveAttachment, dr.GetInt32("LeaveAttachmentID").Value);
            leaveAttachment.LeaveEntryID = dr.GetInt32("LeaveEntryID").Value;
            leaveAttachment.AttachmentPath = dr.GetString("AttachmentPath");
            this.SetObjectState(leaveAttachment, Ease.Core.ObjectState.Saved);
        }

        #region Service Implementation

        public LeaveEntry GetMaternityLeave(int empID, string code)
        {
            LeaveEntry oLeaveEntry = new LeaveEntry();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetMaternityLeave(tc, empID, code));
                if (dr.Read())
                {
                    oLeaveEntry = this.CreateObject<LeaveEntry>(dr);
                }
                dr.Close();
                tc.End();

            }
            catch (Exception ex)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(ex);
                throw new ServiceException("Failed to Get Leave Information" + ex.Message, ex);
                #endregion
            }
            return oLeaveEntry;
        }

        public List<LeaveEntry> Get(int empId, DateTime fromDate, DateTime toDate, EnumLeaveStatus leaveStatus)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, empId, fromDate, toDate, (int)leaveStatus));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }
            return oLeaveEntrys;
        }
        public LeaveEntry Get(int id)
        {
            LeaveEntry oLeaveEntry = new LeaveEntry();

            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, id));
                if (dr.Read())
                {
                    oLeaveEntry = this.CreateObject<LeaveEntry>(dr);
                }

                dr.Close();
                tc.End();
            }
            catch (Exception ex)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(ex);
                throw new ServiceException("Failed to Get Leave Information" + ex.Message, ex);

                #endregion
            }

            return oLeaveEntry;
        }

        /* Uswed for WFTraversPath */
        public LeaveEntry Get(TransactionContext tc, int id)
        {
            LeaveEntry oLeaveEntry = new LeaveEntry();

            try
            {
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, id));
                if (dr.Read())
                {
                    oLeaveEntry = this.CreateObject<LeaveEntry>(dr);
                }

                dr.Close();
            }
            catch (Exception ex)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(ex);
                throw new ServiceException("Failed to Get Leave Information" + ex.Message, ex);

                #endregion
            }

            return oLeaveEntry;
        }

        public DataTable GetPendingJobDetail(int ID)
        {
            DataSet oSet;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                oSet = LeaveEntryDA.GetPendingJobDetail(tc, ID);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();

                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Detail" + e.Message, e);

                #endregion
            }

            return oSet.Tables[0];
        }

        public List<LeaveEntry> GetByLeaveID(int nLeaveID, int nEmpID, DateTime fromDate, DateTime toDate)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetByLeaveID(tc, nLeaveID, nEmpID, fromDate, toDate));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(string EmpIds, int? employeeid, int? leaveYearid, int? leaveid,
            DateTime? fromDate, DateTime? toDate, EnumLeaveStatus? leaveStatus, bool? isLfa)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, employeeid, EmpIds, leaveYearid, leaveid,
                    fromDate, toDate, leaveStatus, isLfa));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(string empIds, int leaveYear, EnumLeaveStatus leaveStatus)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, empIds, leaveYear, (int)leaveStatus));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(string empIds, int leaveYear, int leaveId, EnumLeaveStatus leaveStatus, DateTime leaveFromMonth, DateTime leaveToMonth)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, empIds, leaveYear, leaveId, (int)leaveStatus, leaveFromMonth, leaveToMonth));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(DateTime fromDate, DateTime toDate, EnumLeaveStatus leaveStatus)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, fromDate, toDate, (int)leaveStatus));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public DataTable GetSumOfBalance(DateTime fromDate, DateTime toDate, EnumLeaveStatus leaveStatus)
        {
            TransactionContext tc = null;
            DataTable otab = null;
            try
            {
                tc = TransactionContext.Begin();
                otab = LeaveEntryDA.GetSumOfBalance(tc, fromDate, toDate, (int)leaveStatus);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return otab;
        }


        public List<LeaveEntry> GetAll()
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetAll(tc));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(DateTime attnDate)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, attnDate));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetLFAOnMonth(DateTime onMonth, int payrolltypeid)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetLFAOnMonth(tc, onMonth, payrolltypeid));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public bool IsExist(Employee oEmployee, DateTime fromDate, DateTime toDate)
        {
            TransactionContext tc = null;
            bool IsExist = false;
            try
            {
                tc = TransactionContext.Begin();
                IsExist = LeaveEntryDA.IsExist(tc, oEmployee, fromDate, toDate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return IsExist;
        }

        public List<LeaveEntry> Get(string empIds, DateTime fromDate, DateTime toDate, EnumLeaveStatus leaveStatus)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, empIds, fromDate, toDate, (int)leaveStatus));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetPending(int empId, int leaveID, EnumLeaveStatus leaveStatus)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetPending(tc, empId, leaveID, (int)leaveStatus));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(int empId, int leaveYearID)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, empId, leaveYearID));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetByLeaveYear(int nLeaveYear)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetByLeaveYear(tc, nLeaveYear));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(string empIds, DateTime fromDate, DateTime toDate, string leaveStatuss)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.Get(tc, empIds, fromDate, toDate, leaveStatuss));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> Get(string empIds, DateTime fromDate, DateTime toDate, EnumLeaveStatus leaveStatus,
            string sortExpresion)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr =
                    new DataReader(LeaveEntryDA.Get(tc, empIds, fromDate, toDate, (int)leaveStatus, sortExpresion));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetForAdminPanel(int employeeID)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetForAdminPanel(tc, employeeID));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetEmployeeWiseLeaveDetailReport(string empId, DateTime fromDate, DateTime toDate, int leaveType)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetEmployeeWiseLeaveDetailReport(tc, empId, fromDate, toDate, leaveType));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }
            return oLeaveEntrys;
        }
        public List<LeaveEntry> GetEmployeeWiseLeaveDetailReport(string empId, int leaveYear, int leaveType)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetEmployeeWiseLeaveDetailReport(tc, empId, leaveYear, leaveType));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }
            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetEmployeeWiseLeaveDetailReport(int empId, DateTime fromDate, DateTime toDate,
            int leaveType)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr =
                    new DataReader(
                        LeaveEntryDA.GetEmployeeWiseLeaveDetailReport(tc, empId, fromDate, toDate, leaveType));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                LeaveService leaveService = new LeaveService();
                foreach (var oLeaveEntry in oLeaveEntrys)
                {
                    oLeaveEntry.Leave = leaveService.Get(oLeaveEntry.LeaveID);
                }
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oLeaveEntrys;
        }

        public int GetEmployeeLeaveBalance(int empId, int leaveYear, int leaveType)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                int amount = LeaveEntryDA.GetEmployeeLeaveBalance(tc, empId, leaveYear, leaveType);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }
        }

        public double GetLeaveAmtByType(int empId, int leaveParamId, int leaveYear, EnumLeaveStatus leaveStatus)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                double amount = LeaveEntryDA.GetLeaveAmtByType(tc, empId, leaveParamId, leaveYear, (int)leaveStatus);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }
        }
        public List<LeaveEntry> GetLeaveEntries(int empId, int leaveYearID)
        {
            List<LeaveEntry> oLeaveEntrys = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetLeaveEntries(tc, empId, leaveYearID));
                oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }
            return oLeaveEntrys;
        }

        public List<LeaveEntry> GetSumOfAvailedLeave(int empId, int leaveYearID)
        {
            TransactionContext tc = null;
            List<LeaveEntry> avliedLeaveSum = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetSumOfAvailedLeave(tc, leaveYearID, empId));
                //if (dr.Read())
                {
                    avliedLeaveSum = this.CreateObjectForSums(dr);
                }
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return avliedLeaveSum;
        }

        public List<LeaveEntry> GetSumOfAvailedLeave(int leaveYearID)
        {
            TransactionContext tc = null;
            List<LeaveEntry> avliedLeaveSum = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetSumOfAvailedLeave(tc, leaveYearID));
                avliedLeaveSum = this.CreateObjectForSums(dr);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return avliedLeaveSum;
        }

        public double GetAvailedLeave(int empId, int leaveId, int leaveYear, EnumLeaveStatus leaveStatus)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                double amount = LeaveEntryDA.GetAvailedLeave(tc, empId, leaveId, leaveYear, (int)leaveStatus);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }
        }

        public double GetTotalLeaveAmountInYear(int empId, int leaveYearId, int leaveID, EnumLeaveStatus leaveStatus)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                double amount = LeaveEntryDA.GetTotalLeaveAmountInYear(tc, empId, leaveYearId, leaveID, leaveStatus);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }
        }

        public double GetAmountOnFromDate(int empId, int leaveYearId, int leaveID, EnumLeaveStatus leaveStatus,
            DateTime startdate, DateTime enddate)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                double amount = LeaveEntryDA.GetAmountOnFromDate(tc, empId, leaveYearId, leaveID, leaveStatus,
                    startdate, enddate);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }
        }

        public double GetAmountOnFromDate(int empId, int leaveID, EnumLeaveStatus leaveStatus,
    DateTime startdate, DateTime enddate)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                double amount = LeaveEntryDA.GetAmountOnFromDate(tc, empId, leaveID, leaveStatus,
                    startdate, enddate);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }
        }

        #region Old Code

        /*
        public double GetSubmittedAmt(int empId, int leaveParamId, int leaveYear)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                return LeaveEntryDA.GetSubmittedAmt(tc, empId, leaveParamId, leaveYear);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to GetLeaveEntrys", e);
                #endregion
            }
            return 0;

        }
        public double GetApprovedAmt(int empId, int leaveParamId, int leaveYear)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                return LeaveEntryDA.GetApprovedAmt(tc, empId, leaveParamId, leaveYear);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to GetLeaveEntrys", e);
                #endregion
            }
            return 0;

        }
        public double GetAvailedAmt(int empId, int leaveParamId, int leaveYear)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                return LeaveEntryDA.GetAvailedAmt(tc, empId, leaveParamId, leaveYear);
                tc.End();
            }
            catch (Exception e) 
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to GetLeaveEntrys", e);
                #endregion
            }
            return 0;

        }
        */

        #endregion

        public bool SaveValidation(LeaveEntry lEntry, LeaveYear lyear, Employee employee)
        {
            LeaveYear oLvYear = lyear;
            if (oLvYear == null) oLvYear = new LeaveYearService().Get(lEntry.LeaveYearId);
            Leave oleave = new LeaveService().Get(lEntry.LeaveID);
            List<Employee> employeeList = new List<Employee>();
            employeeList.Add(employee);
            List<EmpLeaveStatus> leaveStatusList = new LeaveProcessService().GetLeaveBalance(employeeList, oLvYear, employee.PayrollTypeID);
            lEntry.Leave = oleave;
            //     lEntry.Leave = new LeaveService().Get(lEntry.LeaveID);
            if (!lEntry.Leave.AllowNegativeBalance)
            {
                var leaveStatus = leaveStatusList.Find(x => x.LeaveId == lEntry.LeaveID);
                if (leaveStatus == null) leaveStatus = new EmpLeaveStatus();
                if (lEntry.Leave.IsBalanceCalculationNeeded && (leaveStatus.ClosingBalance <= 0 || leaveStatus.ClosingBalance < lEntry.AppliedTotalDays))
                {
                    throw new Exception("You do not have enough leaves");
                }
                if (lEntry.Leave.IsBalanceCalculationNeeded)
                {
                    int onApprovalLeaveCount = this.GetOnApprovalLeaveCount(employee.ID, lEntry.LeaveID, lEntry.LeaveYearId, EnumLeaveStatus.OnApproval);

                    if((leaveStatus.ClosingBalance - onApprovalLeaveCount) < lEntry.AppliedTotalDays)
                    {
                        throw new Exception("You are out of balance. You already have pending " + lEntry.Leave.Description);
                    }
                }

            }

            if (lEntry.AppliedFromDate > lEntry.AppliedToDate)
            {
                throw new Exception("To date can not be less than from date");
            }

            //if (lEntry.AppliedFromDate.Year < DateTime.Today.Year)
            //{
            //    throw new Exception("You can not apply for “Leave” on previous year");
            //}

            if (oleave.RemarksNeeded && string.IsNullOrWhiteSpace(lEntry.Remarks))
            {
                throw new Exception("Reason is Needed");
            }

            if (lEntry.AppliedFromDate.Date > oLvYear.EndDate.Date || lEntry.AppliedToDate.Date > oLvYear.EndDate.Date)
            {
                throw new Exception("Your leave date range exceeds the current leave year");
            }

            //if (oLeave.Code.ToUpper() == "CL" || oLeave.Code.ToUpper() == "SL")
            //{
            //    if (closingBalance <= 0 && closingBalance < AppliedTotalDays)
            //    {
            //        throw new CustomException(EnumExceptionType.Validation, string.Format("You can not apply for “{0} Leave” as the balance is zero or less than the number of applied days.", oLeave.Code.ToUpper() == "CL" ? "Casual" : "Blocked"));
            //    }
            //}

            //if (oLeave.Code.ToUpper() == "AL")
            //{
            //    if ((currentLeaveStatus.OpeningBalance - currentLeaveStatus.LeaveAvailed) < AppliedTotalDays)
            //    {
            //        throw new CustomException(EnumExceptionType.Validation, "Total days exceeding your available balance");
            //    }
            //    if (isLFA)
            //    {
            //        if (ResponsiblePersonID == null || ResponsiblePersonID.Integer == 0)
            //        {
            //            throw new CustomException(EnumExceptionType.Validation, "Responsible Person cannot be empty.");
            //        }
            //    }
            //}

            //if (oLeave.Code.ToUpper() == "ML")
            //{

            //    HREmployee oHREmp = new HREmployee().Get(oEmployee.EmployeeNo);
            //    List<LeaveEntry> oLeaveEntries = LeaveEntry.GetByLeaveID(oLeave.ID.Integer, oEmployee.ID.Integer, oEmployee.JoiningDate, DateTime.Today);

            //    if (AppliedTotalDays > 180)
            //    {
            //        throw new CustomException(EnumExceptionType.Validation, "You Cannot apply for more than 6 Months");
            //    }

            //    if ((currentLeaveStatus.OpeningBalance - currentLeaveStatus.LeaveAvailed) < AppliedTotalDays)
            //    {
            //        throw new CustomException(EnumExceptionType.Validation, "Total days exceeding your available balance");
            //    }
            //    //TimeSpan dt = DateTime.Today - oEmployee.JoiningDate;
            //    //if (dt.Days < 120)
            //    //{
            //    //    throw new Exception("You are not eligible for Maternity Leave!!!Eligible service length=120 Days.");
            //    //}

            //}



            List<LeaveEntry> oLEs = new List<LeaveEntry>();
            int currentLeaveEntryID = lEntry.ID;
            oLEs = this.Get(string.Empty, lEntry.EmpID, lEntry.LeaveYearId, null,
                lEntry.AppliedFromDate, lEntry.AppliedToDate, null, null);

            oLEs = oLEs.Where(x => x.LeaveStatus != EnumLeaveStatus.Declined && x.LeaveStatus != EnumLeaveStatus.Cancel
                                             && x.ID != currentLeaveEntryID).ToList();


            // Previous Logic
            //oLEs = LeaveEntry.Get(oEmployee.ID.Integer.ToString(), AppliedFromDate, ApprovedToDate, EnumLeaveStatus.Drafted)
            //                 .Where(x => x.LeaveStatus != EnumLeaveStatus.Declined
            //                             || (x.LeaveStatus == EnumLeaveStatus.Declined && x.LeaveID.Integer == oLeave.ID.Integer && LeaveDayPeriod.Trim().ToUpper() == x.LeaveDayPeriod.Trim().ToUpper()))
            //                 .ToList();

            if (oLEs.Count > 0)
            {
                throw new Exception("Overlap with previously applied leaves.");
            }

            //if (LeaveEntry.IsAttachmentAplicable(oLeave, (decimal)AppliedTotalDays))
            //{
            //    if (this.Attachments == null || this.Attachments.Count <= 0)
            //    {
            //        throw new CustomException(EnumExceptionType.Validation, "Medical documents for sick leave needs to be attached");
            //    }
            //}


            return true;
        }

        public int GetOnApprovalLeaveCount(int empId, int leaveId, int leaveYear, EnumLeaveStatus leaveStatus)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                int count = LeaveEntryDA.GetOnApprovalLeaveCount(tc, empId, leaveId, leaveYear, leaveStatus);
                tc.End();
                return count;
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get OnApproval Leave Count" + e.Message, e);
                #endregion
            }

        }
        public List<LeaveAttachment> GetAllAttachmentsById(int leaveEntry)
        {
            List<LeaveAttachment> items = new List<LeaveAttachment>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader oreader = new DataReader(LeaveEntryDA.GetAttachments(tc, leaveEntry));
                while (oreader.Read())
                {
                    LeaveAttachment item = new LeaveAttachment();
                    item.ID = oreader.GetInt32("LEAVEATTACHMENTID").Value;
                    item.FileAsByteArray = oreader.GetLob("FILEDATA");
                    item.LeaveEntryID = oreader.GetInt32("LEAVEENTRYID").Value;
                    item.FileType = (EnumFileType)oreader.GetInt32("FILETYPE").Value;
                    item.OriginalFileName = oreader.GetString("ORIGINALFILENAME");
                    items.Add(item);
                }

                oreader.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                ExceptionLog.Write(e);

                throw new ServiceException(e.Message, e);

                #endregion
            }

            return items;
        }

        public int Save(LeaveEntry oLeaveEntry)
        {
            TransactionContext tc = null;
            try
            {
                if (oLeaveEntry.Leave == null)
                {
                    oLeaveEntry.Leave = new LeaveService().Get(oLeaveEntry.LeaveID);
                }

                if (oLeaveEntry.Employee == null)
                {
                    oLeaveEntry.Employee = new EmployeeService().Get(oLeaveEntry.EmpID);
                }

                this.SaveValidation(oLeaveEntry, null, oLeaveEntry.Employee);

                tc = TransactionContext.Begin(true);
                Save(oLeaveEntry, tc);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return oLeaveEntry.ID;
        }
        public double GetLeaveExceptionAmtByType(int empId, int leaveId, LeaveException oLeaveEx, EnumLeaveStatus leaveStatus)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                double amount = LeaveEntryDA.GetLeaveExceptionAmtByType(tc, empId, leaveId, oLeaveEx, (int)leaveStatus);
                tc.End();
                return amount;
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }

        }
        public void LeaveApplicationApprove(WFMovementTran approver)
        {
            TransactionContext tc = null;
            try
            {
                SearchEmployee s = new SearchEmployeeService().get(approver.FromEmployeeID);
                LeaveEntry le = new LeaveEntryService().Get(approver.ObjectID);
                Leave oleave = new LeaveService().Get(le.LeaveID);

                tc = TransactionContext.Begin(true);
                string approveString = s.EmployeeNo + "-" + s.Name + ",  has approved your " + oleave.Description + " from "
                    + le.AppliedFromDate.ToString("dd MMM yyyy") + " to " + le.AppliedToDate.ToString("dd MMM yyyy") +
                    " days:" + le.AppliedTotalDays.ToString("0") + ".";
                WFMovementTran newTran = new WFManager<IworkflowInterface>().Approve(tc, approver.ID, approver.FromEmployeeID, approver.Remarks, approveString);

                if (newTran.Status == EnumwfStatus.End)
                {
                    LeaveEntryDA.UpdateLeaveStatus(tc, le.ID, EnumLeaveStatus.Approved);
                    new DailyAttnProcessService().UpdateLeave(tc, le.EmpID, le.LeaveID, approver.UserID, le.ApprovedFromDate, le.ApprovedToDate);
                }
                else
                {
                    LeaveEntryDA.UpdateLeaveStatus(tc, le.ID, EnumLeaveStatus.OnApproval);
                }
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void CancelRequestApprove(WFMovementTran approver)
        {
            TransactionContext tc = null;
            try
            {
                SearchEmployee s = new SearchEmployeeService().get(approver.FromEmployeeID);
                LeaveEntry le = new LeaveEntryService().Get(approver.ObjectID);
                Leave oleave = new LeaveService().Get(le.LeaveID);

                tc = TransactionContext.Begin(true);
                string approveString = s.EmployeeNo + "-" + s.Name + ",  has approved your Cancel Request of " + oleave.Description + " from "
                    + le.AppliedFromDate.ToString("dd MMM yyyy") + " to " + le.AppliedToDate.ToString("dd MMM yyyy") +
                    " days:" + le.AppliedTotalDays.ToString("0") + ".";
                WFMovementTran newTran = new WFManager<IworkflowInterface>().Approve(tc, approver.ID, approver.FromEmployeeID, approver.Remarks, approveString);

                if (newTran.Status == EnumwfStatus.End)
                {
                    LeaveEntryDA.UpdateLeaveStatus(tc, le.ID, EnumLeaveStatus.Cancelled_by_user);
                    new DailyAttnProcessService().UndoLeave(tc, le.EmpID, approver.UserID, le.ApprovedFromDate, le.ApprovedToDate);

                }
                else
                {
                    LeaveEntryDA.UpdateLeaveStatus(tc, le.ID, EnumLeaveStatus.Cancel_Request);
                }
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void ForceReject(TransactionContext tc, int leaveEntryID)
        {
            LeaveEntry oleaveEntry = new LeaveEntryService().Get(leaveEntryID);
            try
            {
                if (oleaveEntry.LeaveStatus == EnumLeaveStatus.Cancel_Request)
                {
                    LeaveEntryDA.UpdateLeaveStatus(tc, leaveEntryID, EnumLeaveStatus.Approved);

                }
                else
                    LeaveEntryDA.UpdateLeaveStatus(tc, leaveEntryID, EnumLeaveStatus.Declined);
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }



        public void ForceComplete(TransactionContext tc, int leaveEntryID)
        {
            LeaveEntry oleaveEntry = new LeaveEntryService().Get(tc, leaveEntryID);

            try
            {
                if (oleaveEntry.LeaveStatus == EnumLeaveStatus.Cancel_Request)
                {

                    LeaveEntryDA.UpdateLeaveStatus(tc, leaveEntryID, EnumLeaveStatus.Cancelled_by_user);
                    new DailyAttnProcessService().UndoLeave(tc, oleaveEntry.EmpID, oleaveEntry.CreatedBy, oleaveEntry.ApprovedFromDate, oleaveEntry.ApprovedToDate);
                }
                else
                {
                    LeaveEntryDA.UpdateLeaveStatus(tc, leaveEntryID, EnumLeaveStatus.Approved);
                    new DailyAttnProcessService().UpdateLeave(tc, oleaveEntry.EmpID, oleaveEntry.LeaveID, oleaveEntry.CreatedBy, oleaveEntry.ApprovedFromDate, oleaveEntry.ApprovedToDate);

                }
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }


        public void LeaveApplicationReject(WFMovementTran rejectTran)
        {
            TransactionContext tc = null;
            try
            {
                SearchEmployee s = new SearchEmployeeService().get(rejectTran.FromEmployeeID);
                LeaveEntry le = new LeaveEntryService().Get(rejectTran.ObjectID);
                Leave oleave = new LeaveService().Get(le.LeaveID);

                tc = TransactionContext.Begin(true);
                string rejectString = s.EmployeeNo + "-" + s.Name + ",  has rejected your " + oleave.Description + " from "
                    + le.AppliedFromDate.ToString("dd MMM yyyy") + " to " + le.AppliedToDate.ToString("dd MMM yyyy") +
                    " days:" + le.AppliedTotalDays.ToString("0") + ".";
                new WFManager<IworkflowInterface>().Reject(tc, rejectTran.ID, rejectTran.FromEmployeeID, rejectTran.Remarks, rejectString);

                LeaveEntryDA.UpdateLeaveStatus(tc, le.ID, EnumLeaveStatus.Declined);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }
        public void CancelRequestReject(WFMovementTran rejectTran)
        {
            TransactionContext tc = null;
            try
            {
                SearchEmployee s = new SearchEmployeeService().get(rejectTran.FromEmployeeID);
                LeaveEntry le = new LeaveEntryService().Get(rejectTran.ObjectID);
                Leave oleave = new LeaveService().Get(le.LeaveID);

                tc = TransactionContext.Begin(true);
                string rejectString = s.EmployeeNo + "-" + s.Name + ",  has rejected your Cancel Request of " + oleave.Description + " from "
                    + le.AppliedFromDate.ToString("dd MMM yyyy") + " to " + le.AppliedToDate.ToString("dd MMM yyyy") +
                    " days:" + le.AppliedTotalDays.ToString("0") + ".";
                new WFManager<IworkflowInterface>().Reject(tc, rejectTran.ID, rejectTran.FromEmployeeID, rejectTran.Remarks, rejectString);

                LeaveEntryDA.UpdateLeaveStatus(tc, le.ID, EnumLeaveStatus.Approved);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void LeaveApplicationRevert(WFMovementTran revertTran)
        {
            TransactionContext tc = null;
            try
            {
                SearchEmployee s = new SearchEmployeeService().get(revertTran.FromEmployeeID);
                LeaveEntry le = new LeaveEntryService().Get(revertTran.ObjectID);

                tc = TransactionContext.Begin(true);
                string revertString = s.EmployeeNo + "-" + s.Name + ",  has Rejected your " + le.LeaveName + ".";
                new WFManager<IworkflowInterface>().Revert(tc, revertTran.ID, revertTran.FromEmployeeID, revertTran.Remarks, revertString);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public int Save(LeaveEntry oLeaveEntry, TransactionContext tc)
        {
            try
            {
                oLeaveEntry.ApprovedTotalDays = oLeaveEntry.AppliedTotalDays;
                bool isNew = oLeaveEntry.IsNew;
                if (oLeaveEntry.IsNew)
                {
                    oLeaveEntry.ID = LeaveEntryDA.GetNewID(tc);

                    LeaveEntryDA.Insert(tc, oLeaveEntry);
                    this.SetObjectID(oLeaveEntry, oLeaveEntry.ID);
                }
                else
                {
                    LeaveEntryDA.Update(tc, oLeaveEntry);
                }

                if (isNew == true && oLeaveEntry.LeaveStatus == EnumLeaveStatus.OnApproval)
                {
                    string subject = oLeaveEntry.Employee.EmployeeNo + "-" + oLeaveEntry.Employee.Name + ",  has applied " + oLeaveEntry.Leave.Description + " from "
                                    + oLeaveEntry.AppliedFromDate.ToString("dd MMM yyyy") + " to " + oLeaveEntry.AppliedToDate.ToString("dd MMM yyyy") +
                                    " days:" + oLeaveEntry.AppliedTotalDays.ToString() + ". Your Approval is required";
                    WFManager<IworkflowInterface> om = new WFManager<IworkflowInterface>(oLeaveEntry);
                    om.InitiateProcess(tc, oLeaveEntry.EmpID, oLeaveEntry.SetupID, oLeaveEntry.ID, "", subject);
                }
                else if(oLeaveEntry.LeaveStatus == EnumLeaveStatus.Approved)
                {
                    new DailyAttnProcessService().UpdateLeave(tc, oLeaveEntry.EmpID, oLeaveEntry.LeaveID, oLeaveEntry.CreatedBy, oLeaveEntry.ApprovedFromDate, oLeaveEntry.ApprovedToDate);

                }
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return oLeaveEntry.ID;
        }

        public void InitiateCancelRequest(LeaveEntry oLeaveEntry)
        {
            Leave oleave = new LeaveService().Get(oLeaveEntry.LeaveID);
            if (oLeaveEntry.Employee == null) oLeaveEntry.Employee = new EmployeeService().Get(oLeaveEntry.EmpID);
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                oLeaveEntry.LeaveStatus = EnumLeaveStatus.Cancel_Request;
                LeaveEntryDA.UpdateLeaveStatus(tc, oLeaveEntry.ID, EnumLeaveStatus.Cancel_Request);
                string subject = oLeaveEntry.Employee.EmployeeNo + "-" + oLeaveEntry.Employee.Name + ",  has applied for Cancellation of  " + oleave.Description + " from "
                                + oLeaveEntry.AppliedFromDate.ToString("dd MMM yyyy") + " to " + oLeaveEntry.AppliedToDate.ToString("dd MMM yyyy") +
                                " days:" + oLeaveEntry.AppliedTotalDays.ToString() + ". Your Approval is required";
                WFManager<IworkflowInterface> om = new WFManager<IworkflowInterface>(oLeaveEntry);
                om.InitiateProcess(tc, oLeaveEntry.EmpID, oLeaveEntry.SetupID, oLeaveEntry.ID, "", subject);

                tc.End();

            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void OnapprovalCancelRequest(int tranId)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);

                LeaveEntryDA.OnapprovalCancelRequest(tc, tranId, EnumLeaveStatus.Cancel, EnumwfStatus.Reject);

                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public List<string> SendMailToTheApproversForCancellation(int tranId, EmailSettings emailSettings)
        {
            DataTable approvarinfo = AllApproverInfo(tranId);
            List<string> errorList = new List<string>();
            string body =
            "Dear <<TOEMPLOYEE>>," +
            "<br/><br/>" +
            "<<APPLIERID>>-<<APPLIERNAME>>, has cancelled <<LEAVENAME>> from <<FROMDATE>> to <<TODATE>> days : <<TOTALDAYS>>.";

            foreach (DataRow item in approvarinfo.Rows)
            {
                try
                {
                    body = body.Replace("<<TOEMPLOYEE>>", item["NAME"].ToString());
                    body = body.Replace("<<APPLIERID>>", item["EMPNO"].ToString());
                    body = body.Replace("<<APPLIERNAME>>", item["EMPLOYEENAME"].ToString());
                    body = body.Replace("<<LEAVENAME>>", item["LEAVENAME"].ToString());
                    body = body.Replace("<<FROMDATE>>", Convert.ToDateTime(item["FROMDATE"].ToString()).ToString("dd MMM yyyy"));
                    body = body.Replace("<<TODATE>>", Convert.ToDateTime(item["TODATE"].ToString()).ToString("dd MMM yyyy"));
                    body = body.Replace("<<TOTALDAYS>>", Convert.ToDouble(item["TOTALDAYS"].ToString()).ToString());

                    MailSender mailSender = new MailSender();
                    mailSender.AddTo(item["EMAILADDRESS"].ToString());
                    mailSender.Subject = "Leave Cancellation";
                    mailSender.Body = "<p>" + body + "</p>";
                    mailSender.SendMail(emailSettings);
                }
                catch (Exception)
                {
                    errorList.Add("Could Not Send Mail to " + item);
                }
            }

            return errorList;
        }

        public DataTable AllApproverInfo(int tranId)
        {
            DataTable tempdt = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);

                tempdt = LeaveEntryDA.AllApproverInfo(tc, tranId);

                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return tempdt;
        }

        public void UplaodFileInProfileUpdate(LeaveAttachment item)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                LeaveEntryDA.UploadFile(tc, item);
                tc.End();
            }

            catch (Exception ex)
            {

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(ex);
                throw new ServiceException("Failed to save file", ex);

            }

        }

        public void SaveLeaveEntryLifFung(List<LeaveEntry> oLeaveEntrys)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                int leaveEntryID = tc.GenerateID("LeaveEntry", "TranId");
                foreach (LeaveEntry lEntry in oLeaveEntrys)
                {
                    if (lEntry.LeaveStatus == EnumLeaveStatus.Approved)
                    {
                        base.SetObjectID(lEntry, leaveEntryID);
                        LeaveEntryDA.Insert(tc, lEntry);

                        new DailyAttnProcessService().UpdateLeaveAndReason(tc, lEntry.EmpID, lEntry.LeaveID, lEntry.CreatedBy, lEntry.ApprovedFromDate, lEntry.ApprovedToDate);

                    }
                    else if (lEntry.LeaveStatus == EnumLeaveStatus.Cancelled_by_user)
                    {
                        //Cancelled_by_user
                        //oItem.ApprovedFromDate, oItem.ApprovedToDate,  empid, fromdate, todate, totaldays, leavestausApprove 
                        LeaveEntryDA.UpdateLeaveStatusLiFung(tc, lEntry);
                        DailyAttnProcessDA.RevertLeaveStatus(tc, lEntry.EmpID, lEntry.LeaveID, lEntry.CreatedBy, lEntry.ApprovedFromDate, lEntry.ApprovedToDate);
                    }
                    leaveEntryID++;
                }
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void SaveLeaveEntry(List<LeaveEntry> oLeaveEntrys)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                SaveLeaveEntry(oLeaveEntrys, tc);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void SaveLeaveEntry(List<LeaveEntry> oLeaveEntry, TransactionContext tc)
        {
            try
            {
                int leaveEntryID = tc.GenerateID("LeaveEntry", "TranId");
                foreach (LeaveEntry lEntry in oLeaveEntry)
                {
                    base.SetObjectID(lEntry, leaveEntryID);
                    LeaveEntryDA.Insert(tc, lEntry);
                    leaveEntryID++;
                }
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void Delete(int id, int userid)
        {
            LeaveEntry ol = new LeaveEntryService().Get(id);
            if (ol.LeaveStatus == EnumLeaveStatus.OnApproval)
            {
                throw new Exception("Not allowed to delete on Approval leave");
            }
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                LeaveEntryDA.Delete(tc, id);
                new DailyAttnProcessService().UndoLeave(tc, ol.EmpID, userid, ol.ApprovedFromDate, ol.ApprovedToDate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        //public void Delete(LeaveEntry oLeaveEntry)
        //{
        //    TransactionContext tc = null;
        //    try
        //    {
        //        int nDays = 0;
        //        tc = TransactionContext.Begin(true);
        //        AttnMonthlyBenefitService attnMonthlyService = new AttnMonthlyBenefitService();
        //        AttendanceProcess attnProcess = new AttendanceProcess();
        //        List<AttnMonthlyBenefit> attnmb = new List<AttnMonthlyBenefit>();
        //        List<DailyAttnProcess> _dAttnProcessess = null;
        //        _dAttnProcessess = new List<DailyAttnProcess>();
        //        Payroll.Service.Attendence.Service.DailyAttnProcessService oAtt = new Payroll.Service.Attendence.Service.DailyAttnProcessService();
        //        DateTime fromDate = oLeaveEntry.ApprovedFromDate.Date;
        //        DateTime toDate = oLeaveEntry.ApprovedToDate.Date;
        //        List<DailyAttnProcess> daProcesses = DailyAttnProcess.Get(oLeaveEntry.EmpID.ToString(), fromDate, toDate);
        //        if (daProcesses != null && daProcesses.Count > 0)
        //        {
        //            nDays = (int)((toDate.Ticks - fromDate.Ticks) / TimeSpan.TicksPerDay) + 1;
        //            DateTime date = fromDate;
        //            for (int i = 1; i <= nDays; i++)
        //            {
        //                DailyAttnProcess dap = daProcesses.Where(o => o.AttnDate == date).FirstOrDefault();
        //                if (dap != null)
        //                {
        //                    if (dap.AttenType == EnumAttendanceType.Leave)
        //                    {
        //                        dap.leaveEntry = null;
        //                        if (dap.InTime == DateTime.MinValue && dap.OutTime == DateTime.MinValue)
        //                        {
        //                            dap.AttenType = EnumAttendanceType.Absent;
        //                            oAtt.UndoAttendanceStatus(tc, oLeaveEntry.EmpID, date, dap.AttenType);
        //                        }
        //                        else if (dap.InTime != DateTime.MinValue && dap.OutTime == DateTime.MinValue)
        //                        {
        //                            dap.AttenType = EnumAttendanceType.Absent;
        //                            oAtt.UndoAttendanceStatus(tc, oLeaveEntry.EmpID, date, dap.AttenType);
        //                        }
        //                        else if (dap.InTime == DateTime.MinValue && dap.OutTime != DateTime.MinValue)
        //                        {
        //                            dap.AttenType = EnumAttendanceType.Absent;
        //                            oAtt.UndoAttendanceStatus(tc, oLeaveEntry.EmpID, date, dap.AttenType);
        //                        }
        //                        else
        //                        {
        //                            dap.AttenType = EnumAttendanceType.Present;
        //                            oAtt.UndoAttendanceStatus(tc, oLeaveEntry.EmpID, date, dap.AttenType);
        //                        }
        //                    }
        //                }
        //                date = date.AddDays(1);
        //            }
        //        }
        //        LeaveEntryDA.Delete(tc, oLeaveEntry.ID);
        //        tc.End();

        //    }
        //    catch (Exception e)
        //    {
        //        #region Handle Exception
        //        if (tc != null)
        //            tc.HandleError();
        //        ExceptionLog.Write(e);
        //        throw new ServiceException(e.Message, e);
        //        #endregion
        //    }

        //}

        public void DeleteByLeaveYear(int nYear, int nLeaveid)
        {
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                LeaveEntryDA.DeleteByLeaveYear(tc, nYear, nLeaveid);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
        }

        public void UpdateStatus(TransactionContext tc, LeaveEntry oItem)
        {
            try
            {
                LeaveEntryDA.UpdateLeaveStatus(tc, oItem.ID, oItem.LeaveStatus);
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Delete Leave Information" + e.Message, e);

                #endregion
            }
        }

        public DataTable GetYearEndData(int leaveYear)
        {
            DataTable oDT = new DataTable();
            oDT.Columns.Add("LeaveId", typeof(Int32));
            oDT.Columns.Add("EmpId", typeof(Int32));
            oDT.Columns.Add("TotalDays", typeof(double));
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetYearEndData(tc, leaveYear));
                //DataReader dr = new DataReader(dr);
                while (dr.Read())
                {
                    DataRow oRow = oDT.NewRow();
                    oRow["LeaveId"] = dr.GetInt32("LeaveId");
                    oRow["EmpId"] = dr.GetInt32("EmpId");
                    oRow["TotalDays"] = dr.GetDouble("TotalDays");
                    oDT.Rows.Add(oRow);
                }

                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oDT;
        }

        public bool IsEntered(DateTime year)
        {
            bool res = false;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                res = LeaveEntryDA.IsEntered(tc, year);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Entry Information" + e.Message, e);

                #endregion
            }

            return res;
        }

        public DataTable GetAvailedLeave(DateTime stDate, DateTime endDate, string empIds)
        {
            DataTable oDT = new DataTable();
            oDT.Columns.Add("EmpId", typeof(Int32));
            oDT.Columns.Add("LeaveId", typeof(Int32));
            oDT.Columns.Add("OrgId", typeof(Int32));
            oDT.Columns.Add("Organization", typeof(System.String));
            oDT.Columns.Add("MonthCode", typeof(Int32));
            oDT.Columns.Add("TotalDays", typeof(double));
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetAvailedLeave(tc, stDate, endDate, empIds));

                while (dr.Read())
                {
                    DataRow oRow = oDT.NewRow();
                    oRow["LeaveId"] = dr.GetInt32("LeaveId");
                    oRow["EmpId"] = dr.GetInt32("EmpId");
                    oRow["OrgId"] = dr.GetInt32("OrgId");
                    oRow["Organization"] = dr.GetString("Organization");
                    oRow["MonthCode"] = 0;
                    oRow["TotalDays"] = dr.GetDouble("TotalDays");
                    oDT.Rows.Add(oRow);
                }

                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oDT;
        }

        public DataTable GetTotalLeaveAmountInYear(int leaveYear, EnumLeaveStatus leaveStatus)
        {
            DataTable oDT = new DataTable();
            oDT.Columns.Add("EmpId", typeof(Int32));
            oDT.Columns.Add("LeaveId", typeof(Int32));
            oDT.Columns.Add("Days", typeof(Int32));
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetTotalLeaveAmountInYear(tc, leaveYear, leaveStatus));

                while (dr.Read())
                {
                    DataRow oRow = oDT.NewRow();
                    oRow["LeaveId"] = dr.GetInt32("LeaveId");
                    oRow["Empid"] = dr.GetInt32("Empid");
                    oRow["Days"] = dr.GetInt32("Days");
                    oDT.Rows.Add(oRow);
                }

                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            return oDT;
        }

        public DataSet GetLeaveReport(int empId, DateTime fromDate, DateTime toDate)
        {
            DataSet oSet;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                oSet = LeaveEntryDA.GetLeaveReport(tc, empId, fromDate, toDate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();

                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Report" + e.Message, e);

                #endregion
            }

            return oSet;
        }

        public DataSet GetAvailedLeave(int empId, DateTime fromDate, DateTime toDate)
        {
            DataSet oSet;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                oSet = LeaveEntryDA.GetAvailedLeave(tc, empId, fromDate, toDate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();

                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Report" + e.Message, e);

                #endregion
            }

            return oSet;
        }
        public DataTable GetMyTeamLeave(int linemanagerid, DateTime fromdate, DateTime todate)
        {
            DataTable dSet = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                dSet = LeaveEntryDA.GetMyTeamLeave(tc, linemanagerid, fromdate, todate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);

                throw new ServiceException(e.Message, e);

                #endregion

            }
            return dSet;
        }
        public DataSet GetRecord(string empIds, DateTime fromDate, DateTime toDate, EnumLeaveStatus leaveStatus)
        {
            DataSet ds = new DataSet();
            DataTable oDT = new DataTable();
            oDT.Columns.Add("TranID", typeof(System.Int64));
            oDT.Columns.Add("Remarks", typeof(System.String));
            oDT.Columns.Add("Description", typeof(System.String));
            oDT.Columns.Add("AppLeaveDate", typeof(System.String));
            oDT.Columns.Add("AprFromDate", typeof(System.String));
            oDT.Columns.Add("AprToDate", typeof(System.String));
            oDT.Columns.Add("AprTotalDays", typeof(System.String));
            oDT.Columns.Add("LeaveStatus", typeof(System.String));
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetRecord(tc, empIds, fromDate, toDate, (int)leaveStatus));

                while (dr.Read())
                {
                    DataRow oRow = oDT.NewRow();
                    oRow["TranID"] = dr.GetDouble("TranID");
                    oRow["Remarks"] = dr.GetString("Remarks");
                    oRow["AprFromDate"] = Convert.ToDateTime(dr.GetString("AprFromDate")).ToString("dd MMM yyyy");
                    oRow["AprToDate"] = Convert.ToDateTime(dr.GetString("AprToDate")).ToString("dd MMM yyyy");
                    oRow["AprTotalDays"] = dr.GetString("AprTotalDays");
                    oRow["Description"] = dr.GetString("Description");
                    oRow["AppLeaveDate"] = Convert.ToDateTime(dr.GetString("AppLeaveDate")).ToString("dd MMM yyyy");
                    short x = (short)dr.GetInt16("LeaveStatus");
                    switch (x)
                    {
                        case 0:
                            oRow["LeaveStatus"] = "Drafted";
                            break;
                        case 1:
                            oRow["LeaveStatus"] = "Waiting for Approval";
                            break;
                        case 2:
                            oRow["LeaveStatus"] = "Approved";
                            break;
                        case 3:
                            oRow["LeaveStatus"] = "reverted";
                            break;
                        case 4:
                            oRow["LeaveStatus"] = "Declined";
                            break;
                        case 5:
                            oRow["LeaveStatus"] = "Approved";
                            break;
                        case 6:
                            oRow["LeaveStatus"] = "Approved";
                            break;
                        case 9:
                            oRow["LeaveStatus"] = "Requested for Cancel";
                            break;
                        case 10:
                            oRow["LeaveStatus"] = "Cancelled";
                            break;
                    }

                    oDT.Rows.Add(oRow);
                }

                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);

                #endregion
            }

            ds.Tables.Add(oDT);
            return ds;
        }

        public DataSet GetReport(string query)
        {
            DataSet oSet;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                oSet = LeaveEntryDA.GetReport(tc, query);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();

                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Report" + e.Message, e);

                #endregion
            }

            return oSet;
        }

        public List<LeaveAttachment> GetAttachments(int leaveEntryID)
        {
            TransactionContext tc = null;
            List<LeaveAttachment> leaveAttachments = null;
            LeaveAttachment leaveAttachment = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetAttachments(tc, leaveEntryID));
                leaveAttachments = new List<LeaveAttachment>();
                while (dr.Read())
                {
                    leaveAttachment = new LeaveAttachment();
                    MapLeaveAttachmentObject(leaveAttachment, dr);
                    leaveAttachments.Add(leaveAttachment);
                }

                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Attachment Information" + e.Message, e);

                #endregion
            }

            return leaveAttachments;
        }

        #region methods for WorkFlow

        internal protected static void UpdateForWF(TransactionContext tc, LeaveEntry leaveEntry)
        {
            LeaveEntryDA.Update(tc, leaveEntry);
        }

        public List<LeaveEntry> GetLFAOnMonth(DateTime onMonth)
        {
            throw new NotImplementedException();
        }

        public void Delete(LeaveEntry oLeaveEntry)
        {
            throw new NotImplementedException();
        }

        #endregion

        public List<HolidayCalendar> getCalenderByLocatin(List<HolidayCalendar> items, int locationID, int payrollTypeID)
        {

            List<Location> locs = new LocationService().Get(EnumStatus.Regardless, payrollTypeID);
            List<HolidayCalendar> locItems = items.FindAll(x => x.LocationID == locationID); // Region
            if (locItems == null || locItems.Count == 0)
            {
                Location loc = locs.FirstOrDefault(x => x.ID == locationID);
                Location parent = locs.FirstOrDefault(x => x.ID == loc.ParentID);
                if (parent != null)
                    locItems = items.FindAll(x => x.LocationID == parent.ID); // Zone
            }
            if (locItems == null || locItems.Count == 0)
            {
                locItems = items.FindAll(x => x.LocationID == null || x.LocationID == 0); // Entire Company
            }

            return locItems;
        }

        private void ThrowMessageForMinimumDays(Leave leave, double calculatedDays)
        {
            if (leave.HasMinimumDays && leave.MinimumDays < calculatedDays)
                throw new Exception($"You have to take this leave for minimum {leave.MinimumDays} days!");
        }

        public double CalculatedLeaveDays(int leaveid, int itemid, int locationID, EnumLeaveparamOn paramType, int payrollTypeid,
            DateTime FromDate, DateTime ToDate, bool fistHalf, bool SecondHalf, bool IsHalfDay, int employeeId)
        {
            if (FromDate == DateTime.MinValue || ToDate == DateTime.MinValue) return 0;
            if (FromDate.Date > ToDate.Date) return 0;
            double nDays = 0;
            bool bIgnoreHoliday = false;
            int sandwichLeave = 0;
            int nDiff = 0;
            int totalDayOff = 0;

            WorkPlanGroup workPlanGroup = new WorkPlanGroupService().GetByEmpId(employeeId);
            LeaveParameter oLeaveParam = new LeaveParameterService().GetApplicableParam(itemid, paramType, leaveid);
            totalDayOff = new ActingResponsibilitySetupService().GetTotalDayOff(employeeId, FromDate, ToDate);
            bIgnoreHoliday = oLeaveParam == null ? false : oLeaveParam.IgnoreHoliday;
            Leave leaveType = new LeaveService().Get(leaveid);


            if (workPlanGroup != null)
            {
                List<AttnNationalHoliday> _attnNationalHolidays;
                AttnNationalHoliday holiday = null;
                DateTime dtStart = FromDate.Date;

                _attnNationalHolidays = new AttnNationalHolidayService().GetByMonthAndPayrollTypeWithDetails(FromDate.Date, ToDate.Date, payrollTypeid);

                for (int i = 0; dtStart <= ToDate.Date; i++)
                {
                    holiday = new AttnNationalHolidayService().GetHoliday(_attnNationalHolidays, dtStart.Date, locationID, workPlanGroup.ID);

                    if (!bIgnoreHoliday) // ignore holiday == true => consider holiday as normal day
                    {
                        dtStart = dtStart.AddDays(1);
                        nDays++;
                    }
                    else if (dtStart.ToString("dddd").ToLower() == workPlanGroup.HolidayOne.ToString().ToLower())
                    {
                        dtStart = dtStart.AddDays(1);
                        continue;
                    }
                    else if (dtStart.ToString("dddd").ToLower() == workPlanGroup.HolidayTwo.ToString().ToLower())
                    {
                        dtStart = dtStart.AddDays(1);
                        continue;
                    }
                    else if (holiday != null)
                    {
                        dtStart = dtStart.AddDays(1);
                        continue;
                    }
                    else
                    {
                        dtStart = dtStart.AddDays(1);
                        nDays++;
                    }
                }
                nDays += sandwichLeave;
                nDays -= bIgnoreHoliday ? totalDayOff : 0;
                ThrowMessageForMinimumDays(leaveType, nDays > 0 ? (IsHalfDay ? (nDays - 0.5) : nDays) : 0);
                return nDays > 0 ? (IsHalfDay ? (nDays - 0.5) : nDays) : 0;
            }
            else
            {
                nDays = 0;

                workPlanGroup = null;
                LeaveParameterService lservice = new LeaveParameterService();
                LeaveParameter lp = lservice.GetApplicableParam(itemid, paramType, leaveid);
                if (lp == null) return 0;
                AttnNationalHolidayService holidays = new AttnNationalHolidayService();
                #region MyRegion

                nDiff = (int)(ToDate - FromDate).Days + 1;
                if (lp != null && lp.IgnoreHoliday)
                {

                    HolidayCalendarService hcService = new HolidayCalendarService();
                    List<HolidayCalendar> oItems = new List<HolidayCalendar>();
                    oItems = hcService.GetbyDateRange(FromDate, ToDate);
                    oItems = this.getCalenderByLocatin(oItems, locationID, payrollTypeid);
                    if (oItems == null) oItems = new List<HolidayCalendar>();

                    var results = from p in oItems
                                  group p by p.HolidayDate into g
                                  select g;
                    foreach (var hc in results)
                    {
                        if (hc.Key >= FromDate && hc.Key <= ToDate)
                        {
                            nDays += 1;
                        }
                    }
                }

                if (lp.CalculationType == EnumLeaveCalculationType.Hourly_365Day)
                {
                    nDays = (nDiff - nDays) > 0 ? (nDiff - nDays) * 8 : 0;
                }
                else if (lp.CalculationType == EnumLeaveCalculationType.Days_365)
                {
                    nDays = (nDiff - nDays) > 0 ? nDiff - nDays : 0;
                }
                else
                {
                    nDays = (nDiff - nDays) > 0 ? nDiff - nDays : 0;
                }

                nDays -= totalDayOff;
                ThrowMessageForMinimumDays(leaveType, IsHalfDay && nDays == 1 ? nDays - 0.5 : nDays);
                return IsHalfDay && nDays == 1 ? nDays - 0.5 : nDays;
            }

            #endregion
        }

        public double GetApplicableDays(Leave oLeave, Employee oEmployee, DateTime FromDate, DateTime ToDate, bool IsHalfDay = false)
        {
            if (FromDate == DateTime.MinValue || ToDate == DateTime.MinValue) return 0;
            if (FromDate.Date > ToDate.Date) return 0;
            if (oLeave == null) return 0;
            if (oEmployee == null) return 0;
            int nDays = 0;
            bool bIgnoreHoliday = false;
            int sandwichLeave = 0;
            int nDiff = 0;

            //int nDiff = (int)((ToDate.Date.Ticks - FromDate.Date.Ticks) / TimeSpan.TicksPerDay) + 1;

            LeaveParameter oLeaveParam = new LeaveParameterService().ApplicableParam(oEmployee, oLeave.ID);
            bIgnoreHoliday = oLeaveParam == null ? false : oLeaveParam.IgnoreHoliday;

            //if (!bIgnoreHoliday) // ignore holiday == true => consider holiday as normal day
            //{
            //    return nDiff > 0 ? (IsHalfDay ? nDiff - 0.5 : nDiff) : 0;
            //}

            WorkPlanGroup workPlanGroup = new WorkPlanGroupService().Get(oEmployee);

            if (workPlanGroup != null)
            {
                List<AttnNationalHoliday> _attnNationalHolidays;
                AttnNationalHoliday holiday = null;
                DateTime dtStart = FromDate.Date;

                _attnNationalHolidays = new AttnNationalHolidayService().GetByMonthAndPayrollType(FromDate.Date, ToDate.Date, oEmployee.PayrollTypeID);

                for (int i = 0; dtStart <= ToDate.Date; i++)
                {
                    holiday = new AttnNationalHolidayService().GetHoliday(_attnNationalHolidays, dtStart.Date, oEmployee.LocationID ?? 0, workPlanGroup.ID);

                    if (!bIgnoreHoliday) // ignore holiday == true => consider holiday as normal day
                    {
                        dtStart = dtStart.AddDays(1);
                        nDays++;
                    }
                    else if (dtStart.ToString("dddd").ToLower() == workPlanGroup.HolidayOne.ToString().ToLower())
                    {
                        dtStart = dtStart.AddDays(1);
                        continue;
                    }
                    else if (dtStart.ToString("dddd").ToLower() == workPlanGroup.HolidayTwo.ToString().ToLower())
                    {
                        dtStart = dtStart.AddDays(1);
                        continue;
                    }
                    else if (holiday != null)
                    {
                        dtStart = dtStart.AddDays(1);
                        continue;
                    }
                    else
                    {
                        dtStart = dtStart.AddDays(1);
                        nDays++;
                    }
                }
                nDays += sandwichLeave;
                return nDays > 0 ? (IsHalfDay ? (nDays - 0.5) : nDays) : 0;
            }
            else
            {
                List<HolidayCalendar> oItems = new HolidayCalendarService().GetWeeklyAndLocHoliday(oEmployee.LocationID);
                nDays = oItems.Where(x => x.HolidayDate.Date >= FromDate.Date && x.HolidayDate.Date <= ToDate.Date && bIgnoreHoliday).Count();
                return (nDiff - nDays) > 0 ? (IsHalfDay ? (nDiff - nDays) - 0.5 : (nDiff - nDays)) : 0;
            }

        }

        public LeaveEntry RefreshObject(int responsiblePersonID, string address, int leaveid, Employee oEmployee, DateTime FromDate, DateTime Todate, 
            double TotalDays, string Reason, string LeaveDayPeriod, EnumHalf SelectedHalf, int userid,
            int LeaveEntryID = 0, bool isLFA = false, bool IsHalfDay=false)
        {
            //LeaveParameter oLeaveParameter = null;
            LeaveEntry _oLeaveEntry = null;

            //oLeaveParameter = new LeaveParameterService().ApplicableParam(oEmployee, leaveid);
            //if (oLeaveParameter == null)
            //{
            //    throw new CustomException(EnumExceptionType.Validation, "Setup not found for " + oLeave.Description);
            //}
            LeaveYear currentLeaveYear = new LeaveYearService().GetCurrentYear(oEmployee.PayrollTypeID);
            if (currentLeaveYear == null)
            {
                throw new CustomException(EnumExceptionType.Validation, "Current Leave Year not set");
            }

            //if (address.Trim() == string.Empty)
            //{
            //    throw new CustomException(EnumExceptionType.Validation, "Please enter Address");
            //}

            if (LeaveEntryID == 0)
            {
                _oLeaveEntry = new LeaveEntry();
                _oLeaveEntry.EmpID = oEmployee.ID;
                _oLeaveEntry.DesignationID = oEmployee.DesignationID ?? 0;
                _oLeaveEntry.DepartmentID = oEmployee.DepartmentID ?? 0;
                _oLeaveEntry.EmpGradeId = oEmployee.GradeID ?? 0;
                _oLeaveEntry.LocationID = oEmployee.LocationID ?? 0;
                _oLeaveEntry.LeaveYearId = currentLeaveYear.ID;
                _oLeaveEntry.ApprovedBy = 1;
                _oLeaveEntry.AvailedBy = oEmployee.ID;
                _oLeaveEntry.AppliedLeaveDate = DateTime.Today;
                _oLeaveEntry.IsAvailed = 0;
                _oLeaveEntry.AvailRemarks = address != null ? address.Trim() : string.Empty;
                _oLeaveEntry.LeaveEntryType = 0;
              
                _oLeaveEntry.CreatedBy = leaveid;
                _oLeaveEntry.CreatedDate = DateTime.Today;
            }
            else
            {
                _oLeaveEntry = new LeaveEntryService().Get(LeaveEntryID);
                _oLeaveEntry.ModifiedBy = userid;
                _oLeaveEntry.ModifiedDate = DateTime.Today;
            }

            //_oLeaveEntry.ApprovedParamId = oLeaveParameter.ID;
            //_oLeaveEntry.AppliedParamId = oLeaveParameter.ID;
            _oLeaveEntry.LeaveID = leaveid;
            _oLeaveEntry.AppliedTotalDays = TotalDays;
            _oLeaveEntry.ApprovedTotalDays = _oLeaveEntry.AppliedTotalDays;
            _oLeaveEntry.AppliedFromDate = FromDate;
            _oLeaveEntry.AppliedToDate = Todate;
            _oLeaveEntry.ApprovedFromDate = _oLeaveEntry.AppliedFromDate;
            _oLeaveEntry.ApprovedToDate = _oLeaveEntry.AppliedToDate;
            _oLeaveEntry.Remarks = Reason;
            _oLeaveEntry.ResponsiblePersonID = responsiblePersonID;
            _oLeaveEntry.AvailRemarks = address != null ? address.Trim() : "";
            _oLeaveEntry.IsDrafted = 0;
            _oLeaveEntry.isLFA = isLFA;
            _oLeaveEntry.IsHalfday = IsHalfDay;
            _oLeaveEntry.SelectedHalf = SelectedHalf;

            if (string.IsNullOrWhiteSpace(LeaveDayPeriod))
            {
                _oLeaveEntry.LeaveDayPeriod = LeaveDayPeriod;
            }
            _oLeaveEntry.LeaveStatus = EnumLeaveStatus.OnApproval;

            return _oLeaveEntry;

        }


        public List<LeaveEntry> GetEmployeeWiseLeaveDetailReport(string empIds, DateTime fromDate, DateTime toDate)
        {
            List<LeaveEntry> oLeaveEntrys = new List<LeaveEntry>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();

                if (string.IsNullOrEmpty(empIds))
                {
                    oLeaveEntrys = new List<LeaveEntry>();
                }
                else
                {

                    DataReader dr = new DataReader(LeaveEntryDA.GetEmployeeWiseLeaveDetailReport(tc, empIds, fromDate, toDate));
                    oLeaveEntrys = this.CreateObjects<LeaveEntry>(dr);
                    dr.Close();
                }
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }
            return oLeaveEntrys;
        }

        public List<LeaveEntryDetailsMailSenderReport> GetPreviousDateApprovedLeaveEntry(DateTime leaveApprovedDate, string salesHeadEmailAddress, EnumLeaveStatus leaveStatus)
        {
            List<LeaveEntryDetailsMailSenderReport> oLeaveEntrys = new List<LeaveEntryDetailsMailSenderReport>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetPreviousDateApprovedLeaveEntry(tc, leaveApprovedDate, salesHeadEmailAddress, leaveStatus));
                while (dr.Read())
                {
                    oLeaveEntrys.Add(this.CreateObjectForSchedular(dr));
                }
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }
            return oLeaveEntrys;
        }

        //For Single employee Leave Ledger Mobile App
        public List<LeaveLedgerMobile> GetEmpLeaveLedger(int empId, DateTime fromDate, DateTime toDate)
        {
            List<LeaveLedgerMobile> oLeaveLedgerMobiles = new List<LeaveLedgerMobile>();
            TransactionContext tc = null;
            try 
            { 
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetEmpleaveLedger(tc, empId, fromDate, toDate));
                while (dr.Read())
                {
                    oLeaveLedgerMobiles.Add(this.CreateObjectForLeaveLedgerMobile(dr));
                }
                dr.Close();
                tc.End();
            }
            catch(Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion

            }
            return oLeaveLedgerMobiles;
        }


        //For Team Upcoming Leave Mobile App
        public List<LeaveLedgerMobile> GetMyTeamUpcomingLeave(int empId, DateTime fromDate, DateTime toDate)
        {
            List<LeaveLedgerMobile> oLeaveLedgerMobiles = new List<LeaveLedgerMobile>();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin();
                DataReader dr = new DataReader(LeaveEntryDA.GetMyTeamUpcomingLeave(tc, empId, fromDate, toDate));
                while (dr.Read())
                {
                    oLeaveLedgerMobiles.Add(this.CreateObjectForLeaveLedgerMobile(dr));
                }
                dr.Close();
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion

            }
            return oLeaveLedgerMobiles;
        }
        public string UploadLeaveAttachment(int leaveId, string fileName, byte[] fileData)
        {
            // for mobile application
            string base64String = string.Empty;
            LeaveAttachment item = new LeaveAttachment();
            string extension = Path.GetExtension(fileName);

            item.OriginalFileName = fileName;
            item.LeaveEntryID = leaveId;
            item.FileType = extension == ".pdf" ? EnumFileType.PDF : EnumFileType.Image;
            using (var ms = new MemoryStream())
            {
                new MemoryStream(fileData).CopyTo(ms);
                item.FileAsByteArray = ms.ToArray();
                byte[] textAsBytes = ms.ToArray();
                new LeaveEntryService().UplaodFileInProfileUpdate(item);
                base64String = Convert.ToBase64String(textAsBytes);
            }

            return base64String;
        }

        public DataTable GetMultipleLeaveLedgerData(int leaveYearId, int leaveId, string empIds, DateTime fromDate, DateTime toDate)
        {
            TransactionContext tc = null;
            DataTable dt = null;
            try
            {
                tc = TransactionContext.Begin();
                fromDate = fromDate.FirstDateOfMonth();
                toDate = toDate.LastDateOfMonth();
                dt = LeaveEntryDA.GetMultipleLeaveLedgerData(tc, leaveYearId, leaveId, empIds, fromDate, toDate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }

            return dt;
        }

        public DataTable GetMultipleLeaveLedgerData(int leaveYearId, string empIds, DateTime fromDate, DateTime toDate)
        {
            TransactionContext tc = null;
            DataTable dt = null;
            try
            {
                tc = TransactionContext.Begin();
                fromDate = fromDate.FirstDateOfMonth();
                toDate = toDate.LastDateOfMonth();
                dt = LeaveEntryDA.GetMultipleLeaveLedgerData(tc, leaveYearId, empIds, fromDate, toDate);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception
                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException("Failed to Get Leave Information" + e.Message, e);
                #endregion
            }

            return dt;
        }


        public DataSet GetAnnualLeave(int empId)
        {
            DataSet dsetDSB = new DataSet();
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                dsetDSB = LeaveEntryDA.GetAnnualLeave(tc, empId);
                tc.End();
            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }

            return dsetDSB;
        }

        public DataTable GetLeaveTodayAndNextWeek(Employee oEmp, EnumLeaveStatus status)
        {
            DataTable dt = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                dt = LeaveEntryDA.GetLeaveTodayAndNextWeek(tc, oEmp, status);
                tc.End();

            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
            return dt;
        }

        public DataTable getTopLeaveChartData(Employee oEmp, int leaveYearId, EnumLeaveStatus status)
        {
            DataTable dt = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                dt = LeaveEntryDA.getTopLeaveChartData(tc, oEmp, leaveYearId, status);
                tc.End();

            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
            return dt;
        }
        public DataTable getcorehrLeaveChartData(Employee oEmp, int leaveYearId, EnumLeaveStatus status)
        {
            DataTable dt = null;
            TransactionContext tc = null;
            try
            {
                tc = TransactionContext.Begin(true);
                dt = LeaveEntryDA.getcorehrLeaveChartData(tc, oEmp, leaveYearId, status);
                tc.End();

            }
            catch (Exception e)
            {
                #region Handle Exception

                if (tc != null)
                    tc.HandleError();
                ExceptionLog.Write(e);
                throw new ServiceException(e.Message, e);

                #endregion
            }
            return dt;
        }
        #endregion

    }

    #endregion
}