using DevExpress.Web;
using System;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class Masters_TA_UI_Master_GeoAttendance : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Common objcommon = new cls_Common();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DemoVersion objDemoVersion = new DemoVersion();
    DataSet ds_Checkuser = new DataSet();
    int EmployeeID = 0;
    string source_Language;
    LeaveEventData objLeave = new LeaveEventData();
    Licensing objLicense = new Licensing();
    string strScript = string.Empty;
    ResetPwd obj_ResetPwd = new ResetPwd();
    int isTriggered = 0;
    ShiftExchangeEventData objShiftExchange = new ShiftExchangeEventData();
    Geofencing objgeo = new Geofencing();
    int intIndividualUser = 0;
    Int64 geoLandMarkID = 0;
    string gstrUserGroupName = string.Empty;
    ShiftEvenData objShift = new ShiftEvenData();
    ManualEntryEventData objManualEntry = new ManualEntryEventData();
    DateTime dTShiftDate = DateTime.Now;
    DataSet dsGridView = new DataSet();
    //EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Common objClassCommon = new cls_Common();
    int intShiftId;
    #endregion
    String punchType = String.Empty;
    private string spunchType;

    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);

        if (!IsPostBack)
        {
            base.CheckPages(326);
            objClassCommon.menu("Geofencing", "326");
            //Set UserRights
            Userrights();
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            LoadStrings(ci);

            StringBuilder map = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type='text/javascript' src='" + ConfigurationManager.AppSettings["googleMapKey"].ToString() + "'></script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptsKey", sb.ToString());
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "loadMapControl();";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("MaxLengthh", strSetAlert);
            hdnEmployeeId.Value = Convert.ToString(Session["EmployeeCodeId"]);
            hdnEmployeeAutoId.Value = Convert.ToString(Session["EmpAutoID"]);
            DisableBtnControls(hdnEmployeeId.Value);
            DateTime shiftDate = DateTime.Now;
            string strShiftDate = shiftDate.ToString("yyyy-MM-dd");
            EmployeeAlocatedFecningLocation(hdnEmployeeAutoId.Value, strShiftDate);
            hdnDateFormat.Value = "dd/MM/yyyy";
            hdnTimeFormat.Value = Convert.ToString(Session["ITimeFormat"]);
            BindGridData();

        }

    }

    private void EmployeeAlocatedFecningLocation(string hdnEmpId, string strShiftDate)
    {

        DataSet ds = new DataSet();
        ds = objgeo.GetEmployeeAllocatedFencingDetails(Convert.ToInt32(hdnEmpId), strShiftDate, "EF");

        hdnSelectedLat.Value = " ";
        hdnSelectedLong.Value = " ";
        hdnFencingId.Value = Convert.ToString(ds.Tables[0].Rows.Count > 0 ? Convert.ToString(ds.Tables[0].Rows.Count) : "");
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                hdnSelectedLat.Value += row["latitude"] + ",";
                hdnSelectedLong.Value += row["longitude"] + ",";
            }
            string jsScript = string.Empty;
            string viewLandmark = "<script>";
            if (hdnEmpId == "1" && hdnLatitude.Value != "" && hdnLongitude.Value != "")
            {
                viewLandmark += "ScrollUp();";
                viewLandmark += " FencingPolygon(1,1);";
            }
            else if (hdnEmpId != "1" && hdnLatitude.Value != "" && hdnLongitude.Value != "")
            {
                viewLandmark += "ScrollUp();";
                viewLandmark += " FencingPolygon(" + hdnLatitude.Value + "," + hdnLongitude.Value + "); ";
            }
            else
            {
                viewLandmark += "ScrollUp();";
                viewLandmark += "FencingPolygon(1,1);";
            }
            viewLandmark += "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "viewLandmark", viewLandmark, false);
        }
        else if (Convert.ToString(hdnEmployeeId.Value) != "18000000")
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Geofencing is not Allocated');", true);
            //DisableBtnControls();
        }

    }

    private void LoadStrings(CultureInfo ci)
    {

        lbl_Header.Text = rm.GetString("WebClockInOut_PageHeader", ci);

        lnkbtnBreakIn.Text = rm.GetString("PunchType_BreakIn", ci);
        lnkbtnBreakOut.Text = rm.GetString("PunchType_BreakOut", ci);
        lnkbtnClockIn.Text = rm.GetString("WebClockInOut_ClockIn", ci);
        lnkbtnClockOut.Text = rm.GetString("WebClockInOut_ClockOut", ci);

        //ToDo: I need to change this condition after completion of development 

    }

    private void DisableBtnControls(string EmployeeCodeID)
    {
        if (EmployeeCodeID == "18000000")
        {
            lnkbtnClockOut.Visible = false;
            lnkbtnClockIn.Visible = false;
            lnkbtnBreakIn.Visible = false;
            lnkbtnBreakOut.Visible = false;
        }

    }

    private void Userrights()
    {
        //if (ViewState["vs_ds_Checkuser"] == null)
        //{
        //    ds_Checkuser = objCheckUser.checkRights(326, Convert.ToInt32(Session["userGroup_Id"]), "");
        //    ViewState["vs_ds_Checkuser"] = ds_Checkuser;
        //}
        //else
        //    ds_Checkuser = (DataSet)ViewState["vs_ds_Checkuser"];
        ds_Checkuser = objCheckUser.checkRights(326, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {

            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                this.grvAttendance.Columns[3].Visible = true;
            }
            else
            {
                this.grvAttendance.Columns[3].Visible = false;
            }



        }
        else
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }

    protected void lnkbtnSave_Click(object sender, EventArgs e)
    {

        string strShiftDate = dTShiftDate.ToString("dd/MM/yyyy");
        string strShiftTime = dTShiftDate.ToString(hdnTimeFormat.Value);

        string YearID = String.Empty;
        YearID = objgeo.GetCurrentYear();


        LinkButton lnbtn = (LinkButton)sender;
        string strInDate = string.Empty, strOutDate = string.Empty, strManualTimeEntryStatus = string.Empty;
        punchType = lnbtn.CommandName;
        if (Convert.ToString(hdnEmployeeId.Value) != "" && Convert.ToString(hdnisValidepunch.Value) == "true")
        {
            int intCompanyId = base.GetCompanyId(Convert.ToInt32(Session["EmpAutoId"]));
            DataSet dsApprovalSettings = new DataSet();
            ShiftEvenData objShift = new ShiftEvenData();
            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
            if (dsApprovalSettings != null)
            {
                if (dsApprovalSettings.Tables.Count > 0)
                {
                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["webClockInOut"]) == false)
                            strManualTimeEntryStatus = "Approved";
                        else
                            strManualTimeEntryStatus = GetManualTimeEntryStatus(Convert.ToString(hdnEmployeeId.Value));
                    }
                    else
                        strManualTimeEntryStatus = GetManualTimeEntryStatus(Convert.ToString(hdnEmployeeId.Value));
                }
            }
            else
                strManualTimeEntryStatus = "Approved";

            //string DataTimeFormat = DateTime.Now.ToString(hdnDateFormat.Value + " " + hdnTimeFormat.Value);

            string dateee = DateTime.Now.ToString();
            String date1 = DateTime.Now.ToString("yyyy/MM/dd");
            String date2 = DateTime.Now.ToString("hh:mm");
            if (punchType == "Clock In" || punchType == "Lunch In" || punchType == "Break In")
            {

                objManualEntry.InsertGeoAttendanceManualEntry
                (
                    Convert.ToString(hdnEmployeeId.Value),
                    /*DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd"))*/DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd")),
                    /*DateTime.Now.ToString(hdnDateFormat.Value)*/ date1,
                    /*DateTime.Now.ToString(hdnTimeFormat.Value)*/date2,
                    punchType,
                    "",
                    "",
                    "",
                    787,
                    0,
                    "Web " + punchType,
                    0,
                    strManualTimeEntryStatus,
                    dateee,
                    Convert.ToInt32(Session["EmpAutoID"]),
                    YearID, 0, 3,
                   hdnLatitude.Value, hdnLongitude.Value, " "
                   );
                BindGridData();
            }
            else
            {

                objManualEntry.InsertGeoAttendanceManualEntry
                 (
                     Convert.ToString(hdnEmployeeId.Value),
                    DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd")),
                     "",
                     "",
                     "",
                     date1,
                     date2,
                     punchType,
                     0,
                     788,
                     "Web " + punchType,
                     0,
                     strManualTimeEntryStatus,
                     dateee,
                     Convert.ToInt32(Session["EmpAutoID"]),
                     YearID, 0, 3,
                     hdnLatitude.Value, hdnLongitude.Value, " "
                    );

                BindGridData();
                //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + punchType + "' Attendance will be Marked');", true);
            }

            string strAlert = string.Empty;
            strAlert = "alert('" + punchType + " Attendance will be Marked');";
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", strAlert, true);

        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Invalid location');", true);
        }

    }

    private void BindGridData()
    {

        string EmployeeFirstName = String.Empty;
        string Employee_CodeID = (Convert.ToString(hdnEmployeeId.Value) == "18000000" ? string.Empty : Convert.ToString(hdnEmployeeId.Value));
        string StrFromDate = "01/01/1900";
        string StrToDate = "01/01/1900";
        string swipeCardID = string.Empty;
        string UserGroupName = Convert.ToString(Session["UserGroupName"]);
        string Userlevels = Convert.ToString(Session["LevelRights"]);
        string GradeLevel = Convert.ToString(Session["GradeLevel"]);
        int ParentId = Convert.ToInt32(Session["parentLevelId"]);
        string type = string.Empty;
        int isImported = 3;

        dsGridView = objgeo.GetEmployeeLiveAttendance(EmployeeFirstName, Employee_CodeID, StrFromDate, StrToDate, swipeCardID, UserGroupName, Userlevels, GradeLevel, ParentId, type, isImported, Convert.ToInt32(hdnEmployeeAutoId.Value));
        grvAttendance.DataSource = dsGridView.Tables[0];
        grvAttendance.DataBind();
        Session["AttednaceGrid"] = dsGridView;
        UpdGrid.Update();
    }

    //protected void btn_Add_Click(object sender, EventArgs e)
    //{
    //    LinkButton lnbtn = (LinkButton)sender;
    //    string strInDate = string.Empty, strOutDate = string.Empty, strManualTimeEntryStatus = string.Empty;

    //    if (Convert.ToString(hdnEmployeeId.Value) != "" )
    //    {
    //        int intCompanyId = base.GetCompanyId(Convert.ToInt32(Session["EmpAutoId"]));
    //        DataSet dsApprovalSettings = new DataSet();
    //        ShiftEvenData objShift = new ShiftEvenData();
    //        dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
    //        if (dsApprovalSettings != null)
    //        {
    //            if (dsApprovalSettings.Tables.Count > 0)
    //            {
    //                if (dsApprovalSettings.Tables[0].Rows.Count > 0)
    //                {
    //                    if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["webClockInOut"]) == false)
    //                        strManualTimeEntryStatus = "Approved";
    //                    else
    //                        strManualTimeEntryStatus = GetManualTimeEntryStatus(Convert.ToString(hdnEmployeeId.Value));
    //                }
    //                else
    //                    strManualTimeEntryStatus = GetManualTimeEntryStatus(Convert.ToString(hdnEmployeeId.Value));
    //            }
    //        }
    //        else
    //            strManualTimeEntryStatus = "Approved";

    //        if (punchType == "Clock In" || punchType == "Lunch In" || punchType == "Break In")
    //        {
    //            objManualEntry.InsertGeoAttendanceManualEntry
    //            (
    //                Convert.ToString(hdnEmployeeId.Value),
    //                DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd")),
    //                DateTime.Now.ToString("yyyy/MM/dd"),
    //                DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
    //                punchType,
    //                "",
    //                "",
    //                "",
    //                787,
    //                0,
    //                "Web " + punchType + " from",
    //                0,
    //                strManualTimeEntryStatus,
    //                DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
    //                Convert.ToInt32(Session["EmpAutoID"]),
    //               Convert.ToString(ViewState["YearSettings_Id"]), 0, 0,
    //               hdnLatitude.Value, hdnLongitude.Value, " "
    //               );



    //        }
    //        else
    //        {
    //            objManualEntry.InsertGeoAttendanceManualEntry
    //             (
    //                 Convert.ToString(hdnEmployeeId.Value),
    //                 DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd")),
    //                 "",
    //                 "",
    //                 "",
    //                 DateTime.Now.ToString("yyyy/MM/dd"),
    //                 DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
    //                 punchType,
    //                 0,
    //                 788,
    //                 "Web " + punchType + " from",
    //                 0,
    //                 strManualTimeEntryStatus,
    //                 DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
    //                 Convert.ToInt32(Session["EmpAutoID"]),
    //                 Convert.ToString(ViewState["YearSettings_Id"]), 0, 0,
    //                 hdnLatitude.Value, hdnLongitude.Value, " "
    //                );
    //            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + punchType + "' Attendance will be Marked');", true);
    //        }

    //    }
    //    else
    //    {
    //    }
    //}

    public string GetManualTimeEntryStatus(string inEmployeeCodeId)
    {
        DataSet dsReportingPersons = new DataSet();
        string strManualTimeEntryStatus = string.Empty;
        Int64 intReportTo = 0, intLeave_Sanc_Authority = 0;
        dsReportingPersons = objEmployee.GetReportingToSanctionAuthorityByCodeID(inEmployeeCodeId);
        if (dsReportingPersons.Tables.Count > 0)
        {
            if (dsReportingPersons.Tables[0].Rows.Count > 0)
            {
                if (dsReportingPersons.Tables[0].Rows[0]["Reporting_To"] != DBNull.Value && dsReportingPersons.Tables[0].Rows[0]["Reporting_To"].ToString() != string.Empty)
                    intReportTo = Int64.Parse(dsReportingPersons.Tables[0].Rows[0]["Reporting_To"].ToString());
                if (dsReportingPersons.Tables[0].Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dsReportingPersons.Tables[0].Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
                    intLeave_Sanc_Authority = Int64.Parse(dsReportingPersons.Tables[0].Rows[0]["Leave_Sanc_Authority"].ToString());
            }
        }
        if (intReportTo != 0 && intLeave_Sanc_Authority != 0 && intReportTo != intLeave_Sanc_Authority)
            strManualTimeEntryStatus = "Pending";
        else
            strManualTimeEntryStatus = "Forwarded";
        return (strManualTimeEntryStatus);
    }


    protected void btnEdit_Click(object sender, EventArgs e)
    {
        LinkButton btnEdit = (LinkButton)sender;
        ////string str = Convert.ToString(e.GetValue("Emp_Id"));
        string strFencingMarkId = btnEdit.CommandArgument.ToString();

        DataSet dsGrid = (DataSet)Session["AttednaceGrid"];

        dsGrid.Tables[0].DefaultView.RowFilter = "ManualTimeEntry_Id=" + strFencingMarkId;

        DataView dv = dsGrid.Tables[0].DefaultView;

        string EmployeeAutoId = Convert.ToString(dv[0]["Emp_Id"]);
        string strShiftDate = Convert.ToString(dv[0]["ManualTimeEntry_Date"]);
        string strLat = Convert.ToString(dv[0]["Latitude_value"]);
        string strLong = Convert.ToString(dv[0]["Longitude_value"]);

        DateTime dateTime = DateTime.Parse(strShiftDate);
        string StrdtFormat = dateTime.ToString("yyyy-MM-dd");

        hdnLatitude.Value = strLat;
        hdnLongitude.Value = strLong;

        EmployeeAlocatedFecningLocation(EmployeeAutoId, StrdtFormat);
    }
    public void page_init()
    {
        DataSet ds = new DataSet();
        if (Session["AttednaceGrid"] != null)
        {
            ds = (DataSet)Session["AttednaceGrid"];
            grvAttendance.DataSource = ds;
            grvAttendance.DataBind();
        }
    }



}
