using Elwig.Helpers;
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace Elwig.Models.Entities {
    [Table("modifier"), PrimaryKey("Year", "ModId")]
    public class Modifier {
        [Column("year")]
        public int Year { get; set; }

        [Column("modid")]
        public required string ModId { get; set; }

        [Column("active")]
        public bool IsActive { get; set; }

        [Column("redacted")]
        public bool IsRedacted { get; set; }

        [Column("ordering")]
        public int Ordering { get; set; }

        [Column("name")]
        public required string Name { get; set; }

        [Column("abs")]
        public long? AbsValue { get; set; }
        [NotMapped]
        public decimal? Abs {
            get => AbsValue != null ? Season.DecFromDb(AbsValue.Value) : null;
            set => AbsValue = value != null ? Season.DecToDb(value.Value) : null;
        }

        [Column("rel")]
        public double? RelValue { get; set; }
        [NotMapped]
        public decimal? Rel {
            get => (decimal?)RelValue;
            set => RelValue = (double?)value;
        }

        [ForeignKey("Year")]
        public virtual Season Season { get; private set; } = null!;

        public string ValueStr =>
            (Abs != null) ? $"{Utils.GetSign(Abs.Value)}{Math.Abs(Abs.Value).ToString("0." + string.Concat(Enumerable.Repeat('0', Season.Precision)))}\u00a0{Season.Currency.Symbol}/kg" :
            (Rel != null) ? $"{Utils.GetSign(Rel.Value)}{(Math.Abs(Rel.Value) < 0.1m ? "\u2007" : "")}{Math.Abs(Rel.Value):0.00##\u00a0%}" :
            "";

        public string? PublicValueStr => IsRedacted ? null : ValueStr;

        public override string ToString() {
            return Name;
        }
    }
}
