using System;
using System.Data;
using System.Net;
using System.Web;
using Cryptographys;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Collections;

public partial class TA_UI_Valid : Base.BasePage
{
    #region VariableDeclaration
    EmployeeEventData ObjEmployeeEventData = new EmployeeEventData();
    Licensing objLicense = new Licensing();
    string userId, ipAddress, session_Id, res, db_sessionId;
    string strDelarLogo;
    CultureInfo ci;
    ResourceManager rm;
    #endregion
    #region PageLoadEvent
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        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;
        if (!IsPostBack)
        {
            GetImagePath();
            if (Session["sLicNotSupport"] != null && Convert.ToString(Session["sLicNotSupport"]) == "1")
            {
                btnContinueDemoVersion.Visible = false;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_Licensecannotsupportothissystem", ci) + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
                return;
            }
            if (Session["sExpiryDays"] != null && Convert.ToInt32(Session["sExpiryDays"]) < 0)
            {
                btnContinueDemoVersion.Visible = false;
                string licenseUptScript = "";
                licenseUptScript = "<script language='javascript' type='text/javascript'>";
                licenseUptScript += "alert('" + rm.GetString("Alert_YourSoftwareLicenseisexpired", ci) + "');";
                licenseUptScript += " </script>";
                this.RegisterStartupScript("licenseUptScriptExDate", licenseUptScript);
                return;
            }
            if (Session["sModuleExceeds"] != null && Convert.ToString(Session["sModuleExceeds"]) == "1")
            {
                btnContinueDemoVersion.Visible = false;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_Pleaseupdatelicenseaslicenseinformation", ci) + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScriptModuleExceeds", strScript);
                return;
            }
            if (Session["sEmployeeAllow"] != null && Convert.ToString(Session["sEmployeeAllow"]) == "0")
            {
                btnContinueDemoVersion.Visible = false;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_EmployeeCountIsMore_CompareWithLicense", ci) + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
                return;
            }
            if (Session["sTerminalAllow"] != null && Convert.ToString(Session["sTerminalAllow"]) == "0")
            {
                btnContinueDemoVersion.Visible = false;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('" + rm.GetString("Alert_CannotLoginMaximumNoofTerminalshavebeencreated", ci) + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScriptTerminal", strScript);
                return;
            }

            if (Convert.ToString(Session["localMACAdderssForlic"]) != "1A153492A74B" &&
            Convert.ToString(Session["localMACAdderssForlic"]) != "00224DB1924C" &&
            Convert.ToString(Session["localMACAdderssForlic"]) != "ECA86BFF8FBB")
            {

                objLicense.ActivateEmployeeBasedOnLicence("5");
            }
        }
        else
        {
        }
    }
    #endregion
    #region UserDefinedFunctions
    protected void GetImagePath()
    {
        try
        {
            if (System.Configuration.ConfigurationManager.AppSettings["DelarLogo"].ToString() != "")
            {
                strDelarLogo = System.Configuration.ConfigurationManager.AppSettings["DelarLogo"].ToString();
                IMG2.Visible = true;
                IMG2.Src = strDelarLogo;
            }
            else
            {
                IMG2.Visible = false;
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected bool CheckDemo()
    {
        string strScript = "";
        string strInstalledDate = "";
        string strExpiryDate = "";
        //Check expiry date       
        strInstalledDate = System.Configuration.ConfigurationManager.AppSettings["Validate1"].ToString();
        strExpiryDate = System.Configuration.ConfigurationManager.AppSettings["Validate2"].ToString();
        strInstalledDate = Cryptography.Decrypt(strInstalledDate, "TimecheckPhaseI");
        strExpiryDate = Cryptography.Decrypt(strExpiryDate, "TimecheckPhaseI");
        DateTime dtExpDate = DateTime.Parse(strExpiryDate);
        if (DateTime.Compare(DateTime.Now.Date, dtExpDate) >= 0)
        {
            strScript = "<script language='javascript' type='text/javascript'>";
            strScript += "alert('" + rm.GetString("Alert_DemoVersionExpired", ci) + "');";
            strScript += "location.href='License_Activation.aspx';";
            strScript += " </script>";
            this.RegisterStartupScript("Alert1", strScript);
            return false;
        }
        else
        {
            return true;
        }
    }
    /// <summary>
    /// Get the Concurrent User Count details.
    /// </summary>
    /// <param name="concurrentUserCount"></param>
    /// <returns></returns>
    private int GetConcurrentUserCount(int concurrentUserCount)
    {
        DictionaryEntry de = new DictionaryEntry();
        string strCacheData = "";
        foreach (object obj in Cache)
        {
            de = (DictionaryEntry)obj;
            if (de.Key.ToString() != "ActiveYearSetting")
            {
                strCacheData = de.Value.ToString();
                string[] strData = strCacheData.Split(',');
                if (strData.Length > 1)
                {
                    concurrentUserCount = concurrentUserCount + 1;
                }
            }
        }
        return concurrentUserCount;
    }
    private void ConcurrentUserUpdation()
    {
        string strScript = "";
        Boolean Flag = true;
        cls_Common objCommon = new cls_Common();
        string licenseUptScript = "";
        bool status = true;
        DateTime inTime;
        // for concurrent user status checking - code added here                                                    
        ipAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
        String strHostName;
        strHostName = Dns.GetHostName();
        IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
        userId = Convert.ToString(Session["EmployeeId"]);
        DateTime loginTime = DateTime.Now;
        IPAddress[] addr = ipEntry.AddressList;
        string session_name = "a";
        session_Id = Session.SessionID.ToString();
        HttpCookie cookie_Session = new HttpCookie(session_name, session_Id);
        Response.Cookies.Add(cookie_Session);
        //Commented on 14-Feb-2020 11:56 PM by Manikandan.rr
        //int cUserCount = HttpContext.Current.Cache.Count; // cache handling
        int cUserCount = 0;
        string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
        if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
        {
        }
        else
        {
            cUserCount = GetConcurrentUserCount(cUserCount);
            //Commented on 14-Feb-2020 11:56 PM by Manikandan.rr
            //cUserCount = cUserCount - 1;
        }
        if (cUserCount == 0)
        {
            string sUser = Convert.ToString(Cache[userId.ToUpper()]);
            if (sUser == null || sUser == String.Empty)
            {
                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                string userValue = string.Empty;
                userValue = ipAddress.ToString() + "," + loginTime + "," + session_Id;
                HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
                Session["cUserName"] = userId.ToUpper();
                Flag = true;
            }
        }
        else
        {
            string sUser = Convert.ToString(Cache[userId.ToUpper()]);
            if (sUser != null && sUser != String.Empty)
            {
                lbl_Error.Text = "User is currently logged in an another session. If you want kill that session Press Proceed!";
                btn_Proceed.Visible = true;
                btn_Cancel.Visible = true;
                return;
            }
            else
            {
                int concurrentUserCount = 0;
                //Commented on 14-Feb-2020 11:56 PM by Manikandan.rr
                //concurrentUserCount = HttpContext.Current.Cache.Count;
                string sActiveYear = Convert.ToString(Cache["ActiveYearSetting"]);
                if (sActiveYear == null || sActiveYear == String.Empty)
                {
                }
                else
                {
                    //Commented on 14-Feb-2020 11:56 PM by Manikandan.rr
                    //concurrentUserCount = concurrentUserCount - 1;                    
                    concurrentUserCount = GetConcurrentUserCount(cUserCount);
                }
                if (userId.ToLower() != "admin" && concurrentUserCount >= 5)
                {
                    licenseUptScript = "<script language='javascript' type='text/javascript'>";
                    licenseUptScript += "alert('" + rm.GetString("Alert_CannotLoginMaximumNoofConcurrentuser", ci) + "');";
                    licenseUptScript += "location.href='index.aspx';";
                    licenseUptScript += " </script>";
                    this.RegisterStartupScript("licenseUptScript6", licenseUptScript);
                    Flag = false;
                    return;
                }
                else
                {
                    TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                    string userValue = string.Empty;
                    userValue = ipAddress.ToString() + "," + loginTime + "," + session_Id;
                    HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
                    Session["cUserName"] = userId.ToUpper();
                    Flag = true;
                }
            }
        }
        if (Flag == true)
        {
            //To get Last login and Logout time of the specified user               
            DataSet dsLastLogin = new DataSet();
            dsLastLogin = ObjEmployeeEventData.GetLastLoginTime(Convert.ToString(Session["EmployeeId"]));
            string strLastLogin = string.Empty;
            string strLastLogout = string.Empty;
            if (dsLastLogin.Tables[0].Rows.Count > 0)
            {
                if (dsLastLogin.Tables[0].Rows[0]["LastLoginTime"] != DBNull.Value)
                {
                    strLastLogin = dsLastLogin.Tables[0].Rows[0]["LastLoginTime"].ToString();
                }
                if (dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"] != DBNull.Value)
                {
                    strLastLogout = dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"].ToString();
                }
            }
            Session["LastLoginTime"] = strLastLogin;
            Session["LastLogoutTime"] = strLastLogout;
            //Insert or Update Login Time in database table
            try
            {
                ObjEmployeeEventData.InsertUpdateLastLogin(Convert.ToString(Session["EmployeeId"]));
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
            DataSet dsUserGroup = new DataSet();
            dsUserGroup = objCommon.SelectGroupName(Convert.ToInt32(Session["userGroup_Id"]));
            if (dsUserGroup != null)
            {
                if (dsUserGroup.Tables.Count > 0)
                {
                    if (dsUserGroup.Tables[0].Rows.Count > 0)
                    {
                        Session["UserGroupName"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["groupName"]);
                        Session["HasSpecialRights"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["hasSpecialRights"]);
                        Session["IndividualUsers"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["IndividualUsers"]);
                    }
                }
            }
            if (Convert.ToString(Session["Edition"]) == "1" || Convert.ToString(Session["Edition"]) == "2")
            {
                Response.Redirect("Landing.aspx");
            }
            else
            {
                Response.Redirect("DashBoard.aspx");
            }
        }
    }
    #endregion
    #region ButtonEvents
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("Index.aspx");
    }
    protected void btn_Proceed_Click(object sender, EventArgs e)
    {
        if (rbtnEnterprise.Checked == true)
        {
            Session["Edition"] = "3";
            Session["Demo"] = "Enterprise";
            objLicense.EnterpriseGradeUpdation();
        }
        else if (rbtnstandard.Checked == true)
        {
            Session["Edition"] = "1";
            Session["Demo"] = "Standard";
            objLicense.UpdateDefaultGradeForSEFromDemo("SEGrade", 1, Convert.ToInt32(Session["EmpAutoID"]));
        }
        else
        {
            Session["Edition"] = "2";
            Session["Demo"] = "Express";
            objLicense.UpdateDefaultGradeForSEFromDemo("SEGrade", 1, Convert.ToInt32(Session["EmpAutoID"]));
        }
        ObjEmployeeEventData.InsertandUpdateDemoType(Convert.ToString(Session["Demo"]));
        if (Session["EmployeeId"] != null && Session["EmployeeId"].ToString() != "")
        {
            string sUser = Convert.ToString(Cache[Session["EmployeeId"].ToString().ToUpper()]);
            if (sUser != null && sUser != String.Empty)
            {
                ObjEmployeeEventData.InsertUpdateLastLogout(Session["EmployeeId"].ToString());
                HttpContext.Current.Cache.Remove(Session["EmployeeId"].ToString().ToUpper());
            }
            else
            {
                return;
            }
            ipAddress = Request.ServerVariables["REMOTE_ADDR"].ToString();
            DateTime loginTime = DateTime.Now;
            TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
            string userValue = string.Empty;
            userId = Session["EmployeeId"].ToString();
            userValue = ipAddress.ToString() + "," + loginTime + "," + Session.SessionID.ToString();
            HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
            Session["cUserName"] = userId.ToUpper();
            DataSet dsLastLogin = new DataSet();
            dsLastLogin = ObjEmployeeEventData.GetLastLoginTime(userId);
            string strLastLogin = string.Empty;
            string strLastLogout = string.Empty;
            if (dsLastLogin.Tables[0].Rows.Count > 0)
            {
                if (dsLastLogin.Tables[0].Rows[0]["LastLoginTime"] != DBNull.Value)
                {
                    strLastLogin = dsLastLogin.Tables[0].Rows[0]["LastLoginTime"].ToString();
                }
                if (dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"] != DBNull.Value)
                {
                    strLastLogout = dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"].ToString();
                }
            }
            Session["LastLoginTime"] = strLastLogin;
            Session["LastLogoutTime"] = strLastLogout;
            ObjEmployeeEventData.InsertUpdateLastLogin(userId);
            DataSet dsUserGroup = new DataSet();
            cls_Common objCommon = new cls_Common();
            dsUserGroup = objCommon.SelectGroupName(Convert.ToInt32(Session["userGroup_Id"]));
            if (dsUserGroup != null)
            {
                if (dsUserGroup.Tables.Count > 0)
                {
                    if (dsUserGroup.Tables[0].Rows.Count > 0)
                    {
                        Session["UserGroupName"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["groupName"]);
                        Session["HasSpecialRights"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["hasSpecialRights"]);
                        Session["IndividualUsers"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["IndividualUsers"]);
                    }
                }
            }
            if (Convert.ToString(Session["Edition"]) == "1" || Convert.ToString(Session["Edition"]) == "2")
            {
                Response.Redirect("Landing.aspx");
            }
            else
            {
                Response.Redirect("DashBoard.aspx");
            }
        }
    }
    protected void btnContinueDemoVersion_Click(object sender, EventArgs e)
    {
        if (rbtnEnterprise.Checked == true)
        {
            Session["Edition"] = "3";
            Session["Demo"] = "Enterprise";
            objLicense.EnterpriseGradeUpdation();
        }
        else if (rbtnstandard.Checked == true)
        {
            Session["Edition"] = "1";
            Session["Demo"] = "Standard";
            objLicense.UpdateDefaultGradeForSEFromDemo("SEGrade", 1, Convert.ToInt32(Session["EmpAutoID"]));
        }
        else
        {
            Session["Edition"] = "2";
            Session["Demo"] = "Express";
            objLicense.UpdateDefaultGradeForSEFromDemo("SEGrade", 1, Convert.ToInt32(Session["EmpAutoID"]));
        }
        ObjEmployeeEventData.InsertandUpdateDemoType(Convert.ToString(Session["Demo"]));
        bool valid = CheckDemo();
        if (valid)
        {
            ConcurrentUserUpdation();
        }
        else
        {
        }
    }
    protected void btnLicenseRequest_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_LicenseRequest.aspx");
    }
    protected void btnUpdateLicense_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_LicenseFileUpload.aspx");
    }
    #endregion
}
