using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using IndexAttribute = Microsoft.EntityFrameworkCore.IndexAttribute;

namespace Elwig.Models.Entities {
    [Table("wine_origin"), PrimaryKey("HkId"), Index("Name", IsUnique = true)]
    public class WineOrigin {
        [Column("hkid")]
        public string HkId { get; private set; }

        [Column("parent_hkid")]
        public string? ParentHkId { get; private set; }

        [ForeignKey("ParentHkId")]
        public virtual WineOrigin? Parent { get; private set; }

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

        [Column("blnr")]
        public int? BlNr { get; private set; }

        [InverseProperty("Origin")]
        public virtual ISet<WbGem> Gems { get; private set; }

        [InverseProperty("Parent")]
        public virtual ISet<WineOrigin> Children { get; private set; }

        public int Level => (Parent?.Level + 1) ?? 0;

        public string HkIdLevel => $"{new string(' ', Level * 2)}{HkId}";

        public int TotalChildNum => 1 + Children.Select(c => c.TotalChildNum).Sum();

        private int SortKey1 => (Parent?.SortKey1 ?? 0) | (TotalChildNum << ((3 - Level) * 8));
        public int SortKey => SortKey1 | ((Level < 3) ? (-1 >>> (Level * 8 + 8)) : 0);

        public override string ToString() {
            return Name;
        }

        public string OriginString => (Parent != null ? $"{Parent.OriginString} / " : "") + Name;
    }
}