using Caliburn.Micro;
using Gremlin.GremlinData.DBClasses;
using Gremlin.GremlinData.EntityClasses;
using Gremlin.GremlinUtilities;
using Gremlin.MVVM.Models;
using System.Linq;

namespace Gremlin.MVVM.ViewModels
{
	public class CustomDescriptionViewModel : PropertyChangedBase
	{
		private string heading;
		private string descriptionText;
		private string coverletterText;
		private string notes;
		private bool isAvailable;

		public string Heading { get => heading; set { heading = value; NotifyOfPropertyChange(() => Heading); } }
		public string DescriptionText { get => descriptionText; set { descriptionText = value; NotifyOfPropertyChange(() => Heading); } }
		public string CoverletterText { get => coverletterText; set { coverletterText = value; NotifyOfPropertyChange(() => Heading); } }
		public string Notes { get => notes; set { notes = value; NotifyOfPropertyChange(() => Heading); } }
		public bool IsAvailable { get => isAvailable; set { isAvailable = value; NotifyOfPropertyChange(() => Heading); } }

		public override string ToString()
		{
			return $"{Heading}\n{DescriptionText}";
		}

		public static CustomDescriptionViewModel GetCustomDescription(LineItemViewModel lineItemVM)
		{
			string tempOptionNumber;
			CustomDescription customDescription = new();
			using (GremlinContext gremlinContext = new())
			{
				tempOptionNumber = lineItemVM.OptionNumber == "" ? null : lineItemVM.OptionNumber;
				customDescription = gremlinContext.CustomDescriptions.Where(cD => cD.ProductNumber == lineItemVM.ProductNumber && cD.OptionNumber == tempOptionNumber).FirstOrDefault();
			}

			CustomDescriptionViewModel customDescriptionVM = new();
			if (customDescription != null)
			{
				customDescriptionVM.Heading = TexHandler.Replace(customDescription.Heading);
				customDescriptionVM.DescriptionText = TexHandler.Replace(customDescription.DescriptionText);
				customDescriptionVM.CoverletterText = TexHandler.Replace(customDescription.CoverletterText);
				customDescriptionVM.Notes = TexHandler.Replace(customDescription.Notes);
				customDescriptionVM.IsAvailable = true;
			}
			else
			{
				customDescriptionVM = NewDescriptionFromSap(lineItemVM);
			}

			return customDescriptionVM;

		}

		private static CustomDescriptionViewModel NewDescriptionFromSap(LineItemViewModel lineItemVM)
		{
			CustomDescriptionViewModel newCustomDescriptionVM = new()
			{
				DescriptionText = TexHandler.Replace(lineItemVM.SapShortDescription),
				Heading = TexHandler.Replace(lineItemVM.SapShortDescription)
			};

			newCustomDescriptionVM.IsAvailable = CustomDescriptionModel.CreateNewCustomDescription(newCustomDescriptionVM, lineItemVM);

			return newCustomDescriptionVM;
		}
	}
}
