using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.IO;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using CMITech.UMXClient;
using CMITech.UMXClient.Events;
using CMITech.UMXClient.Entities;
using System.Security.AccessControl;
using System.Reflection;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using DevExpress.Web;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                        Started Date  : 12-Aug-2007
* Module          : Terminal Master                                  Last Modified : 14-Aug-2007
* Programmer      : Arun vinoth.T
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Masters_TA_UI_Master_SyncEmployee_Device : Base.BasePage
{
    #region "Variable Declaration"

    ResourceManager rm;
    CultureInfo ci;
    private Dictionary<string, Client> m_clients = null;
    private string m_selectedDevice = null;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    cls_Common objcommon = new cls_Common();
    TerminalEventData objTerminal = new TerminalEventData();
    int EmployeeID = 0;
    string gstrUserGroupName = string.Empty, strScript = string.Empty, source_Language;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        m_clients = new Dictionary<string, Client>();
        m_selectedDevice = "";
        base.Page_Load(sender, e);
        gv_CMITechEmployee.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gv_CMITechExistEmployee.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);

        EmployeeID = Convert.ToInt32(Session["EmpAutoID"]);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "RestoreAlert('" + rm.GetString("Alert_Norecordsfound", ci) + "','" + rm.GetString("Alert_Areyousuretorestore", ci) + "','" + rm.GetString("Alert_Selecteddataisnotindeletedstatus", ci) + "','" + rm.GetString("Alert_Selectdatatorestore", ci) + "','" + rm.GetString("Alert_Nodeletedrecordsavailable", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("RestoreAlert", strSetAlert);
        UserRights();
        if (Session["UserGroupName"] != null)
        {
            gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        }
        if (!IsPostBack)
        {
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
            base.CheckPages(275);
            objcommon.menu("Terminal", "275");
            FillTerminalsDropdown();
            BindGridView();
        }
        DataSet ds = new DataSet();
        btn_add.Focus();
    }
    #endregion
    #region ButtonEvents
    private void connectUmx(bool forceConnect = false)
    {
        // Init client for connect
        Client client = null;
        string serialNumber = initClient(ref client);
#if true // Try to connect
        bool connectOk = false;
        try
        {
            if (forceConnect) connectOk = client.StealConnect(false, false, true, 5000);
            else connectOk = client.Connect(/*false, false, true, 5000*/);
        }
        catch (DeviceNotFoundException ex)
        {
        }
        catch (InvalidSerialNumberException ex)
        {
        }
#endif
        // After trying to connect
        if (connectOk)
        {
            m_clients.Add(m_selectedDevice, client);
        }
        else if (forceConnect)
        {
        }
        else
        {
            connectUmx(true);
        }
    }

    protected void btnsync_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(m_selectedDevice))
        {
            //string strScript = "<script language='javascript' type='text/javascript'>";
            //strScript += "alert('" + rm.GetString("SyncEmployeeAlert_Connectionfail2", ci) + "');";
            //strScript += " </script>";
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);

            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "Please select the Device to be controlled.", true);
            return;
        }
        else
        {
            m_selectedDevice = ddl_TerminalId.SelectedValue;
            string[] isValidIPAddress = m_selectedDevice.Split('.');
            if (isValidIPAddress.Length < 3)
            {
                return;
            }
        }
        //Connect CMI tech Device to timecheck
        connectUmx();

        //Creating datatable to store cmi tech employee info
        DataTable dtlogs = new DataTable();
        dtlogs.TableName = "MyDt";
        dtlogs.Columns.Add("EmployeeName", typeof(string));
        dtlogs.Columns.Add("EmployeeId", typeof(string));

        if (!string.IsNullOrEmpty(m_selectedDevice))
        {
            if (m_clients[m_selectedDevice] != null && m_clients[m_selectedDevice].IsConnected())
            {
                try
                {
                    List<UserInfo> logs = m_clients[m_selectedDevice].GetAllUserInfo();
                    if (logs != null)
                    {
                        foreach (UserInfo userinfo in logs)
                        {
                            string userID = string.Empty;
                            userID = userinfo.UUID;
                            Subject userSubjects = m_clients[m_selectedDevice].GetSubject(userID);
                            string FirstName;
                            string LastName;
                            string SubjectUID;
                            if (userSubjects != null)
                            {
                                FirstName = userSubjects.FirstName;
                                LastName = userSubjects.LastName;
                                SubjectUID = userSubjects.SubjectUID;
                                DataRow dr = dtlogs.NewRow();
                                dr[0] = FirstName + " " + LastName;
                                dr[1] = SubjectUID;
                                dtlogs.Rows.Add(dr);//this will add the row at the end of the datatable                               
                            }
                        }
                        StringWriter swCMItechEmployee = new StringWriter();
                        dtlogs.WriteXml(swCMItechEmployee); //Converting as XML for insertion into TA_Tbl_CMITechSyncEmployeeInfo table
                        string swCMItechEmployeedata = Convert.ToString(swCMItechEmployee);

                        //insert into TA_Tbl_CMITechSyncEmployeeInfo portion
                        objTerminal.InsertCMITechEmployeeInfo(swCMItechEmployeedata);
                    }
                    else
                    {
                        string strScript = "<script language='javascript' type='text/javascript'>";
                        strScript += "alert('" + rm.GetString("SyncEmployeeAlert_Connectionfail2", ci) + "');";
                        strScript += " </script>";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                    }
                }
                catch (DeviceNotFoundException ex)
                {
                    string strScript = "<script language='javascript' type='text/javascript'>";
                    strScript += "alert('" + ex.Message + "');";
                    strScript += " </script>";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                }
            }
            else
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("SyncEmployeeAlert_Connectionfail1", ci) + "');";
                strScript += " </script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
            }
        }
        BindCMITechEmployeeInfoInGrid();
    }
    public static DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);
        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable       
        return dataTable;
    }
    protected void btn_add_Click(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        DataTable dt = ds.Tables.Add("TheData");
        dt.Columns.Add("EmployeeCodeId", typeof(string));
        dt.Columns.Add("EmployeeName", typeof(string));
        dt.Columns.Add("DOJ", typeof(string));
        dt.Columns.Add("Designation", typeof(string));
        dt.Columns.Add("CompanyName", typeof(string));

        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            string EmployeeCodeId = string.Empty;
            string EmployeeName = string.Empty;
            string DOJ = string.Empty;
            string Designation = string.Empty;
            string CompanyName = string.Empty;

            for (int i = 0; i < gv_CMITechEmployee.VisibleRowCount; i++)
            {
                HtmlInputCheckBox chkbox = (HtmlInputCheckBox)gv_CMITechEmployee.FindRowCellTemplateControl(i, (GridViewDataColumn)gv_CMITechEmployee.Columns["EmployeeId"], "chkSelect");
                if (chkbox != null)
                {
                    if (chkbox.Checked == true)
                    {
                        System.Web.UI.WebControls.Label lblEmployeeAutoID = (System.Web.UI.WebControls.Label)gv_CMITechEmployee.FindRowCellTemplateControl(i, (GridViewDataColumn)gv_CMITechEmployee.Columns["EmployeeId"], "lblEmployeeId");
                        if (lblEmployeeAutoID != null)
                        {
                            EmployeeCodeId = lblEmployeeAutoID.Text;
                        }
                        System.Web.UI.WebControls.Label lblEmployeeName = (System.Web.UI.WebControls.Label)gv_CMITechEmployee.FindRowCellTemplateControl(i, (GridViewDataColumn)gv_CMITechEmployee.Columns["EmployeeName"], "lblEmployeeName");
                        if (lblEmployeeName != null)
                        {
                            EmployeeName = lblEmployeeName.Text;
                        }
                        System.Web.UI.WebControls.Label lblDOJ = (System.Web.UI.WebControls.Label)gv_CMITechEmployee.FindRowCellTemplateControl(i, (GridViewDataColumn)gv_CMITechEmployee.Columns["DOJ"], "TxtDOJ");
                        if (lblDOJ != null)
                        {
                            DOJ = lblDOJ.Text;
                        }
                        DropDownList grddlshift1 = (DropDownList)gv_CMITechEmployee.FindRowCellTemplateControl(i, null, "ddlDesignation");
                        if (grddlshift1 != null)
                        {
                            Designation = grddlshift1.SelectedItem.Value;
                        }
                        DropDownList lblCompanyName = (DropDownList)gv_CMITechEmployee.FindRowCellTemplateControl(i, null, "ddlCompany");
                        if (grddlshift1 != null)
                        {
                            CompanyName = lblCompanyName.SelectedItem.Value;
                        }
                        DataRow dr = dt.NewRow();
                        dr[0] = EmployeeCodeId;
                        dr[1] = EmployeeName;
                        dr[2] = DOJ;
                        dr[3] = Designation;
                        dr[4] = CompanyName;
                        dt.Rows.Add(dr);//this will add the row at the end of the datatable
                    }
                }
            }
        }
        if (ds.Tables[0].Rows.Count == 0)
        {
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + rm.GetString("SyncEmployeeAlert_Checkboxnotselected", ci) + "');";
            strScript += " </script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        }

        //insert into TA_Tbl_CMITechSyncEmployeeInfo portion
        try
        {
            objTerminal.InsertCMITechtoEmployeeMaster(ds);
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + rm.GetString("SyncEmployeeAlert_SaveSuccess", ci) + "');";
            strScript += " </script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
            BindGridView();
        }
        catch (Exception ex)
        {
            string strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + rm.GetString("SyncEmployeeAlert_ErrorInSync", ci) + " " + ex.Message + "');";
            strScript += " </script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        }
    }
    protected void btn_Update_Click(object sender, EventArgs e)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('Already exist Records 1');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    #endregion
    #region UserDefinedFunction
    public void BindGridView()
    {
        DataSet ds = new DataSet();
        ds = objTerminal.ShowCMITechEmployeeInGrid();
        gv_CMITechEmployee.DataSource = ds.Tables[0];
        gv_CMITechEmployee.DataBind();
        gv_CMITechExistEmployee.DataSource = ds.Tables[0];
        gv_CMITechExistEmployee.DataBind();

        gv_CMITechExistEmployee.DataSource = ds.Tables[1];
        gv_CMITechExistEmployee.DataBind();
        gv_CMITechExistEmployee.DataSource = ds.Tables[1];
        gv_CMITechExistEmployee.DataBind();

        string strChkIds = string.Empty;
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            strChkIds = strChkIds + Convert.ToString(ds.Tables[0].Rows[i][0]) + ",";
        }
        if (strChkIds != string.Empty && strChkIds != null)
        {
            strChkIds = strChkIds.Substring(0, strChkIds.Length - 1);
            hdnGetAllid.Value = Convert.ToString(strChkIds);
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_TerminalId.Text = rm.GetString("lbl_Device", ci);
        lbl_TerminalMaster.Text = rm.GetString("Menu_SyncEmployee_Title", ci);
        btn_add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        btn_Update.Text = "&nbsp;&nbsp;" + rm.GetString("Grid_Update", ci);
        gv_CMITechEmployee.Columns[2].Caption = rm.GetString("email_EmployeeId", ci);
        gv_CMITechEmployee.Columns[3].Caption = rm.GetString("email_EmployeeName", ci);
        gv_CMITechEmployee.Columns[4].Caption = rm.GetString("EmployeeMaster_DateOfJoining", ci);
        gv_CMITechEmployee.Columns[5].Caption = rm.GetString("EmployeeMaster_Designation", ci);
        gv_CMITechEmployee.Columns[6].Caption = rm.GetString("EntranceMaster_Company", ci);
        lbl_man.Text = rm.GetString("IndicatesMandatoryFields", ci);
        btnsync.Text = "&nbsp;&nbsp;" + rm.GetString("lbl_DeviceDataSync", ci);
        // lblEmployeeList.Text = rm.GetString("lbl_DeviceDataSync", ci);
        gv_CMITecholdEmployee.Columns[1].HeaderText = rm.GetString("email_EmployeeName", ci);
        gv_CMITecholdEmployee.Columns[2].HeaderText = rm.GetString("EmployeeMaster_DateOfJoining", ci);
        gv_CMITecholdEmployee.Columns[3].HeaderText = rm.GetString("EmployeeMaster_Designation", ci);
        gv_CMITecholdEmployee.Columns[4].HeaderText = rm.GetString("EntranceMaster_Company", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(275, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
            {
                this.btn_add.Visible = true;
            }
            else
            {
                this.btn_add.Visible = false;
            }

            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                //view page
            }
            else
            {
                Response.Redirect("MasterLandingPage.aspx");
            }
        }
        else
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
    #endregion
    #region GridviewEvents
    protected void gv_CMITechEmployee_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            System.Web.UI.WebControls.TextBox TxtDOJ = (System.Web.UI.WebControls.TextBox)e.Row.FindControl("TxtDOJ");
            // TxtDOJ.Attributes.Add("onmouseover", "javascript:return DynamicDatePicker('" + Hidden1.Value + "','" + TxtDOJ.ClientID + "')");
            DataSet dsAutoShift = new DataSet();
            DropDownList ddlDesignation = (DropDownList)gv_CMITechEmployee.FindRowCellTemplateControl(e.VisibleIndex, null, "ddlDesignation");
            if (ddlDesignation != null)
            {
                dsAutoShift = objTerminal.SelectDesignationDetails_CMITech();
                if (dsAutoShift != null)
                {
                    if (dsAutoShift.Tables.Count > 0)
                    {
                        if (dsAutoShift.Tables[0].Rows.Count > 0)
                        {
                            ddlDesignation.DataSource = dsAutoShift;
                            ddlDesignation.DataTextField = "TitleName";
                            ddlDesignation.DataValueField = "TitleName";
                            ddlDesignation.DataBind();
                        }
                    }
                }
            }

            DataSet dsCompany = new DataSet();
            DropDownList ddlCompany = (DropDownList)gv_CMITechEmployee.FindRowCellTemplateControl(e.VisibleIndex, null, "ddlCompany");
            if (ddlDesignation != null)
            {
                dsCompany = objTerminal.SelectCompanyDetails_CMITech();
                if (dsCompany != null)
                {
                    if (dsCompany.Tables.Count > 0)
                    {
                        if (dsCompany.Tables[0].Rows.Count > 0)
                        {
                            ddlCompany.DataSource = dsCompany;
                            ddlCompany.DataTextField = "name";
                            ddlCompany.DataValueField = "name";
                            ddlCompany.DataBind();
                        }
                    }
                }
            }

        }
    }
    protected void gv_CMITechExistEmployee_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            DataSet dsAutoShift = new DataSet();
            DropDownList ddlDesignation = (DropDownList)gv_CMITechExistEmployee.FindRowCellTemplateControl(e.VisibleIndex, null, "ddlDesignation");
            if (ddlDesignation != null)
            {
                dsAutoShift = objTerminal.SelectDesignationDetails_CMITech();
                if (dsAutoShift != null)
                {
                    if (dsAutoShift.Tables.Count > 0)
                    {
                        if (dsAutoShift.Tables[0].Rows.Count > 0)
                        {
                            ddlDesignation.DataSource = dsAutoShift;
                            ddlDesignation.DataTextField = "TitleName";
                            ddlDesignation.DataValueField = "TitleName";
                            ddlDesignation.DataBind();
                        }
                    }
                }
            }

            DataSet dsCompany = new DataSet();
            DropDownList ddlCompany = (DropDownList)gv_CMITechExistEmployee.FindRowCellTemplateControl(e.VisibleIndex, null, "ddlCompany");
            if (ddlDesignation != null)
            {
                dsCompany = objTerminal.SelectCompanyDetails_CMITech();
                if (dsCompany != null)
                {
                    if (dsCompany.Tables.Count > 0)
                    {
                        if (dsCompany.Tables[0].Rows.Count > 0)
                        {
                            ddlCompany.DataSource = dsCompany;
                            ddlCompany.DataTextField = "name";
                            ddlCompany.DataValueField = "name";
                            ddlCompany.DataBind();
                        }
                    }
                }
            }

        }
    }
    #endregion
    protected void gv_CMITecholdEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv_CMITecholdEmployee.PageIndex = e.NewPageIndex;
    }
    protected void gv_CMITechNewEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv_CMITechNewEmployee.PageIndex = e.NewPageIndex;
    }
    public void FillTerminalsDropdown()
    {
        DataSet ds_Terminal = new DataSet();
        ds_Terminal = objTerminal.SelectTerminalDetails_CMITech();
        if (ds_Terminal.Tables[0].Rows.Count > 0)
        {
            ddl_TerminalId.DataSource = ds_Terminal;
            ddl_TerminalId.DataTextField = "Terminal_Name";
            ddl_TerminalId.DataValueField = "Terminal_Name";
            ddl_TerminalId.DataBind();
        }
        ds_Terminal.Dispose();
        foreach (ListItem item in ddl_TerminalId.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    private string initClient(ref Client client)
    {
        string ipAddress = m_selectedDevice;
        string serialNumber = "";
        bool checkSerialEnabled = false;
        client = new Client(ipAddress, serialNumber, checkSerialEnabled);
        return serialNumber;
    }
    public void BindCMITechEmployeeInfoInGrid()
    {
        DataSet dsEmployeeInfo = new DataSet();
        dsEmployeeInfo = objTerminal.ShowCMITechEmployeeInGrid();
        if (dsEmployeeInfo.Tables.Count > 0)
        {
            if (dsEmployeeInfo.Tables[0].Rows.Count == 0)
            {
                string strMsg;
                gv_CMITechEmployee.DataSource = "";
                gv_CMITechEmployee.DataBind();
                gv_CMITechEmployee.Visible = false;
                gv_CMITechEmployee.Style.Add("display", "none");
                strMsg = "<script language='javascript'>";
                strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "');window.close();";
                strMsg = strMsg + "</script>";
                Page.RegisterStartupScript("Display", strMsg);
                return;
            }
            else
            {
                gv_CMITechEmployee.Style.Add("display", "block");
                gv_CMITechEmployee.Visible = true;
                gv_CMITechEmployee.DataSource = dsEmployeeInfo;
                gv_CMITechEmployee.DataBind();

                gv_CMITechExistEmployee.Style.Add("display", "block");
                gv_CMITechExistEmployee.Visible = true;
                gv_CMITechExistEmployee.DataSource = dsEmployeeInfo;
                gv_CMITechExistEmployee.DataBind();

                ViewState["Dataset_AutoShift"] = dsEmployeeInfo;
            }
        }
    }

}