using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.IO;
using HBLConsole.Model;

namespace HBLConsole
{
    public class SqlHelper : DbContext
    {
        private volatile static SqlHelper _Instance;
        public static SqlHelper GetInstance => _Instance ?? (_Instance = new SqlHelper());
        private SqlHelper() { }

        private string path
        {
            get
            {
                Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AccessFile\\DB"));
                return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\DB\\{GVL.GeneralConfig.DeviceType.ToString()}_{typeof(VariableInfo).Name}.db";
            }
        }

        private static readonly object addLock = new object();

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite($"FileName={path}");
        }

        public DbSet<VariableInfo> DbObj { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //一对一关系映射
            modelBuilder.Entity<VariableInfo>().HasOne(p => p.AlarmSetProp).WithOne(p => p.VariableInfo).HasForeignKey<AlarmSet>(p => p.VariableInfoId);
            modelBuilder.Entity<AlarmSet>().HasOne(P => P.DiscreteAlarmInfoSet).WithOne(P => P.AlarmSet).HasForeignKey<DiscreteAlarmInfo>(P => P.AlarmSetId);

            ////一对多关系映射
            modelBuilder.Entity<AnalogAlarmModel>().HasOne(p => p.AlarmSet).WithMany(p => p.AnalogAlarmModels).HasForeignKey(p => p.AlarmSetId);
        }

        public List<VariableInfo> GetData()
        {
            Database.EnsureCreated();
            return DbObj.ToList();
        }

        public void Save()
        {
            Database.EnsureCreated();
            SaveChanges();
        }

        public void Add(VariableInfo data)
        {
            DbObj.Add(data);
        }
    }
}
