using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Text;
using System.Threading;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                        Created On  : 12-Aug-2007
* Module          : Leave Policy                                     Modified On : 
* Created By      : Arun Vinoth.T
* Modified By     : 
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Masters_EmpLeave_Remote : Base.BasePage
{
    EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Common objCommon = new cls_Common();
    ResourceManager rm;
    CultureInfo ci;
    // Declarations
    string[] LeaveType = new string[50];
    string[] MaxDays = new string[50];
    int[] LeaveType_Id = new int[50];
    int rows = 0;
    int PolicyId = 0;
    string PolName = "", gstrDateFormat = "", strDOJDate = "";
    int days = 0;
    int EmployeeID = 0;
    int nextId = 1;
    StringBuilder sb = new StringBuilder();
    StringBuilder sb_Emp = new StringBuilder();
    DataTable dt_policy;
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking and reset date format
        base.Page_Load(sender, e);
        //Session.LCID = 1033;
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        try
        {
            EmployeeID = Convert.ToInt32(Session["EmpAutoID"].ToString());
        }
        catch (Exception ex)
        {
            Response.Redirect("../index.aspx");
            Response.Write(ex.ToString());
        }
        string PolicyDetails = "", PolicyValid = "";
        if (Request.QueryString["Details"] != null && Request.QueryString["Details"] != "" && Request.QueryString["validationDate"] != null && Request.QueryString["validationDate"] != "")
        {
            PolicyDetails = Request.QueryString["Details"].ToString();
            PolicyValid = Request.QueryString["validationDate"].ToString();
            strDOJDate = Request.QueryString["DOJDate"].ToString();
        }
        else
        {
            Response.Clear();
            //Response.Write("Fail");
            Response.End();
        }
        if (PolicyDetails == "undefined")
        {
            Response.Clear();
            Response.Write("EmptyFail");
            Response.End();
        }
        else if (PolicyDetails == "MappedPolicy@~%")
        {
            Response.Clear();
            Response.Write("MappedPolicy@~%");
            Response.End();
        }
        dt_policy = null;
        dt_policy = new DataTable();
        Datatable_creation();
        char[] star = { '*' };
        char[] comma = { ',' };
        string[] policies = PolicyDetails.Split(star);
        string[] StartDateArr = new string[10];
        string[] EndDateArr = new string[10];
        for (int i = 0; i < policies.Length; i++)
        {
            string[] details = policies[i].Split(comma);
            if ((details[0] != "") && (details[1] != ""))
            {
                StartDateArr[i] = details[0];
                EndDateArr[i] = details[1];
            }
            else
            {
                Response.Clear();
                Response.Write("EmptyFail");
                Response.End();
            }
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strDOJDate = objCommon.DateConvertion(gstrDateFormat, strDOJDate);
        DateTime dtmDOJDate = DateTime.Parse(strDOJDate);
        for (int i = 0; i < policies.Length; i++)
        {
            string[] details = policies[i].Split(comma);
            PolicyId = Convert.ToInt32(details[2]);
            if ((details[0] != "") && (details[1] != ""))
            {
                string strFromdate = details[0];
                string strTodate = details[1];
                strFromdate = objCommon.DateConvertion(gstrDateFormat, details[0]);
                strTodate = objCommon.DateConvertion(gstrDateFormat, details[1]);
                DateTime start = Convert.ToDateTime(strFromdate);
                DateTime end = Convert.ToDateTime(strTodate);
                days = DateDiff(start, end);
                //for validating Leave policy duration
                string[] date = PolicyValid.Split("*".ToCharArray());
                string strfrom = date[0];
                string strto = date[1];
                DateTime from = Convert.ToDateTime(strfrom);
                DateTime to = Convert.ToDateTime(strto);
                TimeSpan diff = start.Subtract(from);
                TimeSpan diff2 = to.Subtract(start);
                int day = diff.Days;
                int day2 = diff2.Days;
                bool blfrom = true, blto = true;
                if (day < 0)
                    blfrom = false;
                if (day2 < 0)
                    blfrom = false;
                TimeSpan diff1 = end.Subtract(from);
                int day1 = diff1.Days;
                TimeSpan diff3 = to.Subtract(end);
                int day3 = diff3.Days;
                if (day1 < 0)
                    blto = false;
                if (day3 < 0)
                    blto = false;
                TimeSpan diff4 = end.Subtract(start);
                int day4 = diff4.Days;
                if (day4 < 0)
                    blto = false;
                if (strDOJDate != "")
                {
                    if (dtmDOJDate > start)
                    {
                        Response.Clear();
                        Response.Write("DOJFail");
                        Response.End();
                    }
                }
                if (blfrom == false || blto == false)
                {
                    //break;
                    Response.Clear();
                    Response.Write("Fail");
                    Response.End();
                }
                GetLeaveDetails(PolicyId);
                GenerateControls();
            }
            else
            {
                Response.Clear();
                Response.Write("Failure");
                Response.End();
            }
        }
        for (int i = 0; i < policies.Length; i++)
        {
            if (i > 0)
            {
                string strPrevStartDate = StartDateArr[i - 1];
                string strPrevEndDate = EndDateArr[i - 1];
                string strStartDate = StartDateArr[i];
                string strEndDate = EndDateArr[i];
                DateTime dtmPrevStartDate = DateTime.Parse(objCommon.DateConvertion(gstrDateFormat, strPrevStartDate));
                DateTime dtmPrevEndDate = DateTime.Parse(objCommon.DateConvertion(gstrDateFormat, strPrevEndDate));
                DateTime dtmStartDate = DateTime.Parse(objCommon.DateConvertion(gstrDateFormat, strStartDate));
                DateTime dtmEndDate = DateTime.Parse(objCommon.DateConvertion(gstrDateFormat, strEndDate));
                if (dtmStartDate > dtmPrevStartDate && dtmStartDate > dtmPrevEndDate && dtmEndDate > dtmPrevStartDate && dtmEndDate > dtmPrevEndDate)
                {
                }
                else
                {
                    Response.Clear();
                    Response.Write("Interven");
                    Response.End();
                }
            }
        }
        if (Request.QueryString["Qo"] != null)
        {
            if (Convert.ToString(Request.QueryString["Qo"]) == "1")
            {
                GenerateCurrentQuota();
                Response.Clear();
                Response.Write(sb);
                Response.End();
                //return;
            }
        }
        Response.Clear();
        Response.Write(sb_Emp);
        Response.End();
    }
    private void GenerateCurrentQuota()
    {
        //sb.Append("<b>Quota</b><br><br>");
        sb.Append("<table class='table das-table1 TableWidth1'>");
        sb.Append("<tr>");
        sb.Append("<th class='empheader pull-left-button' colspan=2>");
        sb.Append("<b>" + rm.GetString("btn_Leave_Quota", ci) + "</b>");
        sb.Append("</th></tr>");

        DataTable dtQuota = new DataTable();
        dtQuota = (DataTable)Session["Emp_Policy"];
        DataTable dtNew = new DataTable();
        dtNew = dtQuota.DefaultView.ToTable(true, "LeaveTypeId");
        decimal dec = 0;
        DataTable dtTot = new DataTable();
        for (int i = 0; i < dtNew.Rows.Count; i++)
        {
            int iLeaveType = Convert.ToInt16(dtNew.Rows[i][0]);
            dtQuota.DefaultView.RowFilter = " LeaveTypeId=" + dtNew.Rows[i][0];
            dtTot = dtQuota.DefaultView.ToTable();
            double Tot = 0;
            Tot = Convert.ToDouble(dtTot.Compute("Sum(MaxDays)", "1=1"));
            DataSet ds = new DataSet();
            ds = objEmployee.GetCurrentLeaveQuota(Convert.ToInt32(Session["ModifiyEmployeeID"]), iLeaveType);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["LeaveType"] != DBNull.Value)
                {
                    sb.Append("<tr><td>" + ds.Tables[0].Rows[0]["LeaveType"].ToString() + "</td>");
                    if (ds.Tables[0].Rows[0]["Leave_Taken"] != DBNull.Value)
                    {
                        double totalval = 0;
                        totalval = Tot - Convert.ToDouble(ds.Tables[0].Rows[0]["Leave_Taken"]);
                        sb.Append("<td>" + Convert.ToString(totalval) + "</td></tr>");
                    }
                    else
                    {
                        sb.Append(Tot + "</td></tr>");
                    }
                }
            }

            //else
            //{
            //    sb.Append(Tot + "<br>");
            //}
        }
        sb.Append("</table>");
    }
    //function getting leave details
    private void GetLeaveDetails(int policyID)
    {
        DataSet ds = new DataSet();
        ds = objEmployee.select_EmpLeavePolicyDetails(PolicyId);
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                PolName = ds.Tables[0].Rows[0]["PolicyName"].ToString();
                rows = ds.Tables[0].Rows.Count;
                for (int i = 0; i < rows; i++)
                {
                    LeaveType[i] = ds.Tables[0].Rows[i]["LeaveType"].ToString();
                    LeaveType_Id[i] = Convert.ToInt32(ds.Tables[0].Rows[i]["LeaveType_Id"].ToString());
                    int totLeave = Convert.ToInt32(ds.Tables[0].Rows[i]["MaxDays_applicable"]);
                    decimal leaveperday = 0;
                    if (Convert.ToString(ds.Tables[0].Rows[i]["IsProrataRequired"]) == "True")
                    {
                        leaveperday = (Decimal)totLeave / 365;
                        MaxDays[i] = Convert.ToString(Math.Round(days * leaveperday, 0));
                    }
                    else
                    {
                        leaveperday = (Decimal)totLeave;
                        MaxDays[i] = Convert.ToString(Math.Round(1 * leaveperday, 0));
                    }
                    //inserting into Datatable
                    DataRow dr = dt_policy.NewRow();
                    dr["PolicyId"] = PolicyId;
                    dr["LeaveTypeId"] = LeaveType_Id[i];
                    dr["MaxDays"] = MaxDays[i];
                    dr["EmployeeID"] = EmployeeID;
                    dr["LeavePolicyValue"] = nextId;
                    if (Convert.ToDecimal(ds.Tables[0].Rows[i]["MaxDays_Month"]) > 0)
                    {
                        dr["MaxDays_month"] = Convert.ToDecimal(ds.Tables[0].Rows[i]["MaxDays_Month"]);
                    }
                    else
                    {
                        dr["MaxDays_month"] = 0;
                    }
                    dt_policy.Rows.Add(dr);

                    //objEmployee.InsertEmpLeavePolicyDetails(PolicyId, Convert.ToInt32(LeaveType_Id[i]),Convert.ToDecimal(MaxDays[i]), EmployeeID);
                }
                nextId = nextId + 1;
                Session["Emp_Policy"] = dt_policy;
            }
            ds.Dispose();
        }
    }
    //function generates control
    private void GenerateControls()
    {
        sb_Emp.Append("<table id=\"tbl_emp\" class='table das-table1 TableWidth1' >");
        sb_Emp.Append("<tr>");
        sb_Emp.Append("<th class='empheader pull-left-button' colspan=" + rows + ">");
        //sb_Emp.Append("<b>Policy Name</b><br><br>");
        sb_Emp.Append("<label>" + rm.GetString("LeavePermissionPolicy_PolicyName", ci) + "</label> : <b>" + PolName + "</b>");
        //sb_Emp.Append("" + PolName + "");
        sb_Emp.Append("</th>");
        sb_Emp.Append("</tr>");
        sb_Emp.Append("<tr>");
        for (int i = 0; i < rows; i++)
        {
            sb_Emp.Append("<td>");
            sb_Emp.Append("<b>" + LeaveType[i].ToString() + "</b><br><br>");
            sb_Emp.Append("" + MaxDays[i].ToString() + "");
            sb_Emp.Append("</td>");
        }
        sb_Emp.Append("</tr>");
        sb_Emp.Append("</table><br/>");
    }
    private int DateDiff(System.DateTime startDate, System.DateTime endDate)
    {
        System.TimeSpan TS = new System.TimeSpan(endDate.Ticks - startDate.Ticks);
        int diff = Convert.ToInt32(TS.TotalDays);
        return diff;
    }
    private void Datatable_creation()
    {
        DataColumn dc_policyID = dt_policy.Columns.Add("PolicyId", typeof(int));
        DataColumn dc_LeaveTypeID = dt_policy.Columns.Add("LeaveTypeId", typeof(int));
        DataColumn dc_Maxdays = dt_policy.Columns.Add("MaxDays", typeof(decimal));
        DataColumn dc_EmployeeID = dt_policy.Columns.Add("EmployeeID", typeof(int));
        DataColumn dc_leavePolicyValue = dt_policy.Columns.Add("LeavePolicyValue", typeof(int));
        DataColumn dc_Maxdays_Month = dt_policy.Columns.Add("MaxDays_month", typeof(decimal));
    }
}
