namespace PerpetuumSoft.Widgets.Licensing
{
    using Microsoft.Win32;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Windows.Forms;

    public class PerpetuumSoftLicenseProvider : LicenseProvider
    {
        private static int assemblyCount = 0;
        private const string LicensePath = @"Software\Perpetuum Software\License";
        private static Hashtable licenses = null;
        private static Hashtable trialMessages = new Hashtable();

        private PerpetuumSoftLicense CreateDesignTimeLicense(string key, Type type, string option)
        {
            PerpetuumSoftLicense license = null;
            key = LicensingUtilities.DecodeLicenseKey(key);
            if (LicensingUtilities.CheckDesignTimeLicenseKey(key))
            {
                PerpetuumSoftLicense license2 = new PerpetuumSoftLicense(LicensingUtilities.GetDesignTimeLicenseText(LicensingUtilities.ParseLicenseKey(key)));
                if (license2.CheckOption(option))
                {
                    license = license2;
                }
            }
            return license;
        }

        private PerpetuumSoftLicense FindBestLicenceKey(Type type, string option)
        {
            PerpetuumSoftLicense licence = null;
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Perpetuum Software\License"))
            {
                foreach (string str in key.GetValueNames())
                {
                    string str2 = (string) key.GetValue(str, string.Empty);
                    PerpetuumSoftLicense license2 = this.CreateDesignTimeLicense(str2, type, option);
                    if (this.GetLicensePriority(license2, type, option) > this.GetLicensePriority(licence, type, option))
                    {
                        licence = license2;
                    }
                }
            }
            return licence;
        }

        private string GetAllLicenses(string assemblyQualifiedName)
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            if (assemblyCount != assemblies.Length)
            {
                if (licenses == null)
                {
                    licenses = new Hashtable();
                }
                assemblyCount = 0;
                Hashtable hashtable = null;
                while (assemblyCount < assemblies.Length)
                {
                    Assembly assembly = assemblies[assemblyCount];
                    if (!(assembly is AssemblyBuilder))
                    {
                        string str = string.Empty;
                        string str2 = string.Empty;
                        string fileName = assembly.get_EscapedCodeBase();
                        if ((fileName != null) && (fileName.Length > 0))
                        {
                            str = this.GetName(fileName).ToUpper(CultureInfo.InvariantCulture);
                            str2 = str + ".licenses".ToUpper(CultureInfo.InvariantCulture);
                        }
                        string[] manifestResourceNames = assembly.GetManifestResourceNames();
                        for (int i = 0; i < manifestResourceNames.Length; i++)
                        {
                            if ((str2.Length > 0) && (manifestResourceNames[i].ToUpper(CultureInfo.InvariantCulture) == str2))
                            {
                                Stream manifestResourceStream = assembly.GetManifestResourceStream(manifestResourceNames[i]);
                                try
                                {
                                    object obj2 = new BinaryFormatter().Deserialize(manifestResourceStream);
                                    if (obj2 is object[])
                                    {
                                        object obj3 = (obj2 as object[])[0];
                                        if ((obj3 is string) && (((string) obj3) == str))
                                        {
                                            hashtable = (Hashtable) (obj2 as object[])[1];
                                            foreach (string str4 in hashtable.Keys)
                                            {
                                                if (!licenses.Contains(str4))
                                                {
                                                    licenses.Add(str4, hashtable[str4]);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                }
                                finally
                                {
                                    if (manifestResourceStream != null)
                                    {
                                        manifestResourceStream.Dispose();
                                    }
                                }
                            }
                        }
                    }
                    assemblyCount++;
                }
            }
            return (string) licenses[assemblyQualifiedName];
        }

        private PerpetuumSoftLicense GetDesignLicense(Type type)
        {
            string option = ((LicenseOptionAttribute) Attribute.GetCustomAttribute(type, typeof(LicenseOptionAttribute))).Option;
            PerpetuumSoftLicense license = null;
            try
            {
                license = this.FindBestLicenceKey(type, option);
            }
            catch
            {
            }
            if (license == null)
            {
                string licenseKey = ((LicenseAttribute) Attribute.GetCustomAttribute(type.Assembly, typeof(LicenseAttribute))).LicenseKey;
                license = this.CreateDesignTimeLicense(licenseKey, type, option);
            }
            return license;
        }

        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            PerpetuumSoftLicense designLicense = null;
            string text = string.Empty;
            string option = ((LicenseOptionAttribute) Attribute.GetCustomAttribute(type, typeof(LicenseOptionAttribute))).Option;
            if (context.get_UsageMode() == 1)
            {
                designLicense = this.GetDesignLicense(type);
            }
            else
            {
                text = this.GetAllLicenses(type.AssemblyQualifiedName);
                if (text == null)
                {
                    text = string.Empty;
                }
                text = LicensingUtilities.DecodeLicenseKey(text);
                if (LicensingUtilities.CheckRunTimeLicenseKey(text))
                {
                    designLicense = new PerpetuumSoftLicense(text);
                }
                if (designLicense == null)
                {
                    designLicense = this.GetDesignLicense(type);
                }
                if ((designLicense != null) && !designLicense.CheckOption(option))
                {
                    designLicense = null;
                }
            }
            if ((((designLicense == null) || designLicense.IsTrial) || designLicense.IsExpire(type)) && (SystemInformation.get_UserInteractive() || (context.get_UsageMode() == 1)))
            {
                LicenseAttribute customAttribute = (LicenseAttribute) Attribute.GetCustomAttribute(type.Assembly, typeof(LicenseAttribute));
                LicenseHolder holder = (LicenseHolder) Activator.CreateInstance(customAttribute.LicenseHolder, false);
                string licenseAgreement = string.Empty;
                licenseAgreement = holder.LicenseAgreement;
                if (licenseAgreement == null)
                {
                    licenseAgreement = string.Empty;
                }
                if (IsShowTrialMessage(option))
                {
                    using (TrialForm form = new TrialForm(context.get_UsageMode() == 1, designLicense, type, ((LicenseAttribute) Attribute.GetCustomAttribute(type.Assembly, typeof(LicenseAttribute))).ProductName, option, licenseAgreement))
                    {
                        form.Text = type.ToString();
                        form.ShowDialog();
                        designLicense = new PerpetuumSoftLicense(LicensingUtilities.DecodeLicenseKey(((LicenseAttribute) Attribute.GetCustomAttribute(type.Assembly, typeof(LicenseAttribute))).LicenseKey));
                    }
                }
            }
            if (designLicense != null)
            {
                string str5 = LicensingUtilities.EncodeLicenseKey(designLicense.get_LicenseKey(), false);
                context.SetSavedLicenseKey(type, str5);
            }
            return designLicense;
        }

        private long GetLicensePriority(PerpetuumSoftLicense licence, Type type, string option)
        {
            long num = 0L;
            if ((licence != null) && licence.CheckOption(option))
            {
                num = 1L;
                if (!licence.IsTrial)
                {
                    num = this.GetLicensesInGroup(licence) + 1;
                    if (!licence.IsExpire(type))
                    {
                        DateTime epirationDate = licence.EpirationDate;
                        num = ((num * 0xf4240L) + (epirationDate.Year * 0x3e8)) + epirationDate.DayOfYear;
                    }
                }
            }
            return num;
        }

        private int GetLicensesInGroup(PerpetuumSoftLicense licenece)
        {
            int num = 1;
            try
            {
                string s = licenece["LicensesInGroup"];
                if ((s != null) && (s.Length > 0))
                {
                    num = int.Parse(s);
                }
            }
            catch
            {
            }
            return num;
        }

        private string GetName(string fileName)
        {
            Uri uri = new Uri(fileName, true);
            return Path.GetFileName(uri.LocalPath + uri.Fragment);
        }

        private static bool IsShowTrialMessage(string requaredOption)
        {
            int num = 0;
            try
            {
                lock (trialMessages)
                {
                    if (trialMessages.ContainsKey(requaredOption))
                    {
                        num = (int) trialMessages[requaredOption];
                        trialMessages.Remove(requaredOption);
                    }
                    trialMessages.Add(requaredOption, num + 1);
                }
            }
            catch
            {
                num = 0;
            }
            return ((num % 5) == 0);
        }
    }
}
