using SWRIS.Models;
using System;
using System.ComponentModel;
using System.Linq;

namespace SWRIS.Enums
{
    public enum RiskLevel
    {
        /// <summary>
        /// 0 - 正常
        /// </summary>
        [Description("正常")]
        Normal = -1,

        /// <summary>
        /// 0 - 轻微
        /// </summary>
        [Description("轻微")]
        Mild = 0,

        /// <summary>
        /// 1 - 轻度
        /// </summary>
        [Description("轻度")]
        Light = 1,

        /// <summary>
        /// 2 - 中度
        /// </summary>
        [Description("中度")]
        Moderate = 2,

        /// <summary>
        /// 3 - 较重
        /// </summary>
        [Description("较重")]
        Severe = 3,

        /// <summary>
        /// 4 - 严重
        /// </summary>
        [Description("严重")]
        Critical = 4,

        /// <summary>
        /// 5 - 超限
        /// </summary>
        [Description("超限")]
        ExceededLimit = 5

    }

    public static class RiskLevelEvaluator
    {
        public static RiskLevel Evaluate(double maxDamageValue, double avgDamageValue)
        {
            if (maxDamageValue <= 0 && avgDamageValue <= 0)
            {
                return RiskLevel.Normal;
            }
            // Check from highest to lowest severity
            foreach (RiskLevel level in Enum.GetValues(typeof(RiskLevel)).Cast<RiskLevel>().OrderByDescending(x => x))
            {
                var attribute = GetRiskLevelConfig(level);

                // First check max damage range
                bool isMaxRangeMatch = maxDamageValue > attribute.MaxDamageRange.Min && maxDamageValue <= attribute.MaxDamageRange.Max;
                if (isMaxRangeMatch)
                {
                    return level;
                }

                // If max range doesn't match, then check avg damage range
                bool isAvgRangeMatch = avgDamageValue > attribute.AvgDamageRange.Min && avgDamageValue <= attribute.AvgDamageRange.Max;
                if (isAvgRangeMatch)
                {
                    return level;
                }
            }
            return RiskLevel.Normal;
        }
        public static RiskLevelConfig GetRiskLevelConfig(this RiskLevel level)
        {
            return App.Config.RiskLevelSettings.Levels
                  .FirstOrDefault(x => x.Level == level) ?? new RiskLevelConfig
                  {
                      Level = RiskLevel.Normal,
                      MaxDamageRange = new Range { Min = 0, Max = 0 },
                      AvgDamageRange = new Range { Min = 0, Max = 0 },
                  };
        }
    }
}
