using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Management;
using VIZ.Framework.Core;
using VIZ.Framework.Connection;
using VIZ.Framework.Module;
using System.Reflection;

namespace VIZ.Framework.Module
{
    /// <summary>
    /// 应用程序启动 -- 应用程序安全
    /// </summary>
    public class AppSetup_ApplicationSafe : AppSetupBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static ILog log = LogManager.GetLogger(typeof(AppSetup_ApplicationSafe));

        /// <summary>
        /// 描述
        /// </summary>
        public override string Detail { get; } = "应用程序启动 -- 应用程序安全";

        /// <summary>
        /// 执行启动
        /// </summary>
        /// <param name="context">应用程序启动上下文</param>
        /// <returns>是否成功执行</returns>
        public override bool Setup(AppSetupContext context)
        {
            Assembly assembly = Assembly.GetEntryAssembly();

            // Step 1. 应用程序过期时间校验
            ApplicationTimeCheckAttribute time_check = assembly.GetCustomAttribute<ApplicationTimeCheckAttribute>();
            if (time_check != null && time_check.ExpirationTime < DateTime.Now)
            {
                MessageBox.Show("系统校验失败，请联系管理员！");
                return false;
            }

            // Step 2. 应用程序MAC地址校验
            List<string> mac_address_list = this.getAllMacAddressForCheck();
            IEnumerable<ApplicationMacCheckAttribute> mac_check_list = assembly.GetCustomAttributes<ApplicationMacCheckAttribute>();
            if (mac_check_list != null && mac_check_list.Count() > 0 && !mac_check_list.Any(p => mac_address_list.Contains(p.MacAddress)))
            {
                MessageBox.Show("系统校验失败，请联系管理员！");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 执行关闭
        /// </summary>
        /// <param name="context">应用程序启动上下文</param>
        public override void Shutdown(AppSetupContext context)
        {

        }

        /// <summary>
        /// 获取所有用于MAC地址校验的值
        /// </summary>
        /// <returns>用于MAC地址校验的值</returns>
        private List<string> getAllMacAddressForCheck()
        {
            List<string> list = new List<string>();
            foreach (NetHelperMacInfo info in NetHelper.GetAllMacAddressWithDefaultFilter())
            {
                if (!string.IsNullOrWhiteSpace(info.PhysicalAddress))
                {
                    list.Add(info.PhysicalAddress);
                }

                if (!string.IsNullOrWhiteSpace(info.DHCPv6ClientDUID))
                {
                    list.Add(info.DHCPv6ClientDUID);
                }
            }

            return list;
        }
    }
}
