using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Npgsql;
using Register_office.BaseClasses;
using Register_office.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Register_office.ViewModel
{
	internal class ResultViewModel
	{
		private readonly GeneralViewModel _general;

		internal GeneralViewModel General => _general;

		public ResultViewModel()
		{
			_general = GeneralViewModel.Instance;
		}

		public void Update()
		{
			_general.Context.SaveChanges();
		}

		public int AddResult<T>(T type) where T : IUnionId
		{
			try
			{
				switch (typeof(T).Name)
				{
					case "Result":
						_general.Context.Results.Add(type as Result);
						_general.Context.SaveChanges();
						return _general.Context.Results
									.OrderByDescending(x => x.ResultId).First().ResultId;
					case "NumericResult":
						_general.Context.NumericResults.Add(type as NumericResult);
						break;
					case "QualitativeResult":
						_general.Context.QualitativeResults.Add(type as QualitativeResult);
						break;
				}

				_general.Context.SaveChanges();
			}
			catch (DbUpdateException ex)
			{
				DeleteResult(type);
				string message = "";
				if (ex.GetBaseException() is PostgresException pgException)
				{
					if (pgException.ConstraintName != null)
					{
						message = "Нарушено ограничение " + pgException.ConstraintName;
					}
					else
					{
						message = pgException.Message;
					}
				}

				MessageBox.Show(message, "Ошибка добавления",
						MessageBoxButtons.OK, MessageBoxIcon.Error);
				return -1;
			}

			return 0;
		}

		public void DeleteResult<T>(T type) where T : IUnionId
		{
			switch (typeof(T).Name)
			{
				case "Result":
					_general.Context.Results.Remove(type as Result);
					break;
				case "NumericResult":
					_general.Context.NumericResults.Remove(type as NumericResult);
					break;
				case "QualitativeResult":
					_general.Context.QualitativeResults.Remove(type as QualitativeResult);
					break;
			}
			_general.Context.SaveChanges();
		}
	}
}
