using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Common.Helpers;

namespace JiShe.CollectBus.IoTDB.Options
{
    /// <summary>
    /// 查询条件
    /// </summary>
    public class QueryCondition
    {
        /// <summary>
        /// 字段
        /// </summary>
        public string Field { get; set; }

        /// <summary>
        /// 操作符,>，=，<
        /// </summary>
        public string Operator { get; set; }

        /// <summary>
        /// 是否数值，如果是数值，则进行数值比较，否则进行字符串比较
        /// </summary>
        public bool IsNumber { get; set; } = false;
         
        private object _rawValue;
        /// <summary>
        /// 值
        /// </summary>
        public object Value
        {
            get => ApplyValueConversion(_rawValue);
            set => _rawValue = value;
        }

        /// <summary>
        /// 值转换
        /// </summary>
        /// <param name="rawValue"></param>
        /// <returns></returns>
        private object ApplyValueConversion(object rawValue)
        {
            string declaredTypeName = rawValue.GetType().Name;

            Func<object, object> converter = GetQueryConditionValue(declaredTypeName);
            return converter(rawValue);
        }

        /// <summary>
        /// 查询条件值转换委托
        /// </summary>
        /// <param name="declaredTypeName"></param>
        /// <returns></returns>
        private Func<object, object> GetQueryConditionValue(string declaredTypeName)
        {
            return declaredTypeName?.ToUpper() switch
            {
                "DATETIME" => v => v != null ? ((DateTime)v).ToUniversalTime().Ticks : null,
                "STRING" => v => v != null ? $"'{v}'" : "''",
                _ => v => v
            };
        } 
    }
}
