using System;
using System.Data;
using System.IO;
using System.Net.NetworkInformation;

public partial class LicenseUpdater : System.Web.UI.Page
{
    // declaration of required license information variables     
    // objects creation for Licensing class
    Licensing objLicense = new Licensing();
    cls_Common objClassCommon = new cls_Common();
    DongleAuthentication dongleAuthentication = new DongleAuthentication();
    // variable for modules
    int master, transaction, report, organizationSetting, systemSetting;
    // variable for protection table license information
    int dongleId, customerId, softwareId, packageId, noOfConcurrentUser;
    string packageVersion;
    DateTime expiryDate, dateOfIssue;
    // for module information
    string module, module1, module2, module3, module4, module5;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
        else
        {
        }
    }
    public string GetMACAddress()
    {
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        String sMacAddress = string.Empty;
        foreach (NetworkInterface adapter in nics)
        {
            if (sMacAddress == String.Empty)// only return MAC Address from first card  
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                sMacAddress = adapter.GetPhysicalAddress().ToString();
            }
        }
        return sMacAddress;
    }
    protected void btnLicenseUpdation_Click(object sender, EventArgs e)
    {
        // read license key and value to authenticate license
        string licenseValue = System.Configuration.ConfigurationManager.AppSettings["LicenseKey"].ToString();
        if (licenseValue == "LicenseFile")
        {
            string[] fileArr = Directory.GetFiles(Server.MapPath("LicenseFile"), "*.lic");
            int arrCount = fileArr.Length;
            if (arrCount > 0)
            {
                string licenseFileName = fileArr[arrCount - 1].ToString();
                //File Stream pointing to License File,if exist
                FileStream licenseFileStream = new FileStream(licenseFileName, FileMode.Open);
                //Stream Reader pointing to License  File
                StreamReader licenseFileStreamReader = new StreamReader(licenseFileStream);
                // read license file information from .lic file
                string encryptedLicFileInfo = licenseFileStreamReader.ReadToEnd();
                //Close the Streams
                licenseFileStreamReader.Close();
                licenseFileStream.Close();
                string decryptedLicFileInfo = Encryption.Decrypt(encryptedLicFileInfo, "");
                string[] decryptedLicFileInfoArr = decryptedLicFileInfo.Split('#');
                // set basic license info 
                string basicLicInfo = decryptedLicFileInfoArr[0].ToString();
                string[] basicLicInfoArr = basicLicInfo.Split(',');
                // set license file MACAddress
                string macAddressLicFile = basicLicInfoArr[5].ToString();
               
                string localMACAdderss = GetMACAddress();
                // check local and license file MACAddress
                if (macAddressLicFile != localMACAdderss)
                {
                    string strScript = "<script language='javascript' type='text/javascript'>";
                    strScript += "alert('License cannot support to this system');";
                    strScript += " </script>";
                    this.RegisterStartupScript("setScript", strScript);
                    //flag = false;
                    return;
                }
                else
                {
                    //Code added here by prabakaran.p
                    string[] fileArrDelete = Directory.GetFiles(Server.MapPath("LicenseFile"), "*.lic");
                    int arrCountDelete = fileArrDelete.Length;
                    if (arrCountDelete > 0)
                    {
                        for (int i = 0; i < arrCountDelete; i++)
                        {
                            string strlicenseFileName = fileArrDelete[i].ToString();
                            System.IO.FileInfo fileInfoDelete = new System.IO.FileInfo(strlicenseFileName);
                            fileInfoDelete.Delete();
                        }
                    }
                    if (Session["Edition"].ToString() == "0" || Session["Edition"].ToString() == "3")
                    {
                        if (basicLicInfoArr[1].ToString() == "1")
                        {
                            DataSet dsPendingForwarded = new DataSet();
                            dsPendingForwarded = objLicense.SelectLICPendingForwardedRecords();
                            if (dsPendingForwarded.Tables[0].Rows.Count > 0)
                            {
                                string strStatus = string.Empty;
                                strStatus = dsPendingForwarded.Tables[0].Rows[0]["Result"].ToString();
                                if (strStatus != string.Empty)
                                {
                                    Base.BasePage objBaseLIC = new Base.BasePage();
                                    string strScript = "<script language='javascript' type='text/javascript'>";
                                    strScript += "alert('" + strStatus + "');";
                                    strScript += " </script>";
                                    this.RegisterStartupScript("setScript", strScript);
                                    return;
                                }
                            }
                        }
                    }
                    string customerId, packageId, noOfConcurrentUser, noOfEmployee, noOfTerminal, packageVersion, licenseGenerationDate, expiryDate;
                    customerId = basicLicInfoArr[0].ToString();
                    string ecustomerId = Encryption.Encrypt(customerId, "");
                    packageId = basicLicInfoArr[1].ToString();
                    string epackageId = Encryption.Encrypt(packageId, "");
                    packageVersion = basicLicInfoArr[2].ToString();
                    string epackageVersion = Encryption.Encrypt(packageVersion, "");
                    noOfConcurrentUser = basicLicInfoArr[3].ToString();
                    string enoOfConcurrentUser = Encryption.Encrypt(noOfConcurrentUser, "");
                    noOfEmployee = basicLicInfoArr[4].ToString();
                    string enoOfEmployee = Encryption.Encrypt(noOfEmployee, "");
                    string emacAddressLicFile = Encryption.Encrypt(macAddressLicFile, "");
                    licenseGenerationDate = basicLicInfoArr[6].ToString();
                    string elicenseGenerationDate = Encryption.Encrypt(licenseGenerationDate, "");
                    expiryDate = basicLicInfoArr[7].ToString();
                    string eexpiryDate = Encryption.Encrypt(expiryDate, "");
                    noOfTerminal = basicLicInfoArr[8].ToString();
                    string enoOfTerminal = Encryption.Encrypt(noOfTerminal, "");
                    string emodule = "";
                    string emodule1 = "";
                    string emodule2 = "";
                    string emodule3 = "";
                    string emodule4 = "";
                    string emodule5 = "";
                    string pageStatusFalse = string.Empty;
                    // data table for TA_Tbl_Page
                    DataTable dtPageInfo = new DataTable("TA_Tbl_Page");
                    DataColumn dcPageId = new DataColumn("pageId", System.Type.GetType("System.Double"));
                    DataColumn dcDisplayName = new DataColumn("displayName", System.Type.GetType("System.String"));
                    DataColumn dcPath = new DataColumn("path", System.Type.GetType("System.String"));
                    DataColumn dcParentId = new DataColumn("parentId", System.Type.GetType("System.Int32"));
                    DataColumn dcOrderBy = new DataColumn("orderBy", System.Type.GetType("System.Double"));
                    dtPageInfo.Columns.Add(dcPageId);
                    dtPageInfo.Columns.Add(dcDisplayName);
                    dtPageInfo.Columns.Add(dcPath);
                    dtPageInfo.Columns.Add(dcParentId);
                    dtPageInfo.Columns.Add(dcOrderBy);
                    DataRow drPageInfo;
                    for (int i = 0; i < decryptedLicFileInfoArr.Length; i++)
                    {
                        if (i > 0)
                        {
                            string moduleInfo = decryptedLicFileInfoArr[i].ToString();
                            string[] decryptedModuleArr = moduleInfo.Split('*');
                            for (int j = 0; j < decryptedModuleArr.Length; j++)
                            {
                                string[] decryptedModuleColumnArr = decryptedModuleArr[j].ToString().Split(',');
                                if (decryptedModuleColumnArr[3].ToString() == "1")
                                {
                                    drPageInfo = dtPageInfo.NewRow();
                                    drPageInfo.BeginEdit();
                                    drPageInfo["pageId"] = Convert.ToDouble(decryptedModuleColumnArr[1].ToString());
                                    drPageInfo["displayName"] = decryptedModuleColumnArr[4].ToString();
                                    drPageInfo["path"] = decryptedModuleColumnArr[5].ToString();
                                    drPageInfo["parentId"] = Convert.ToInt32(decryptedModuleColumnArr[2].ToString());
                                    drPageInfo["orderBy"] = Convert.ToDouble(decryptedModuleColumnArr[6].ToString());
                                    drPageInfo.EndEdit();
                                    dtPageInfo.Rows.Add(drPageInfo);
                                }
                                else
                                {
                                    if (pageStatusFalse == string.Empty)
                                    {
                                        pageStatusFalse = decryptedModuleColumnArr[1].ToString();
                                    }
                                    else
                                    {
                                        pageStatusFalse = pageStatusFalse + "," + decryptedModuleColumnArr[1].ToString();
                                    }
                                }
                            }
                        }
                    }
                    objLicense.InsertIntoProtectionTable(ecustomerId, epackageId, epackageVersion, enoOfConcurrentUser, enoOfEmployee, enoOfTerminal, emacAddressLicFile, elicenseGenerationDate, eexpiryDate, emodule, emodule1, emodule2, emodule3, emodule4, emodule5, pageStatusFalse);
                    objLicense.InsertIntoTATblPage(dtPageInfo);
                    objLicense.ActivateEmployeeBasedOnLicence(noOfEmployee);
                    objLicense.UpdateUserRightsDetails();
                    int gradeMasterExists = 0;
                    gradeMasterExists = objClassCommon.CheckPageExistsInLicense(228);
                    if (packageId == "1" && gradeMasterExists == 0)
                    {
                        objLicense.UpdateDefaultGradeForSE("SEGrade", 1, Convert.ToInt32(Session["EmpAutoID"]));
                    }
                    else
                    {
                    }
                    string scriptUpdate = "<script language='javascript' type='text/javascript'>";
                    scriptUpdate += "alert('License Information has been updated successfully!');";
                    scriptUpdate += "location.href='Index.aspx';";
                    scriptUpdate += " </script>";
                    this.RegisterStartupScript("scriptLicenseUpdate", scriptUpdate);
                }
            }
            else
            {
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('Please place the license file in the following path " + Server.MapPath("LicenseFile").Replace("\\", "/\\") + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
                return;
            }
        }
        else if (licenseValue == "UniKeyDongle")
        {
        }
        else if (licenseValue == "HaspDongle")
        {
        }
    }
}
