using Gremlin.GremlinData.DBClasses;
using Gremlin.GremlinData.EntityClasses;
using System.Diagnostics;
using System.Linq;

namespace Gremlin.MVVM
{
    public class CustomDescriptionViewModel
    {
        public string Heading { get; set; }
        public string DescriptionText { get; set; }
        public string CoverletterText { get; set; }
        public string Notes { get; set; }    //Hinweise, Tipps, Caveats, etc. für Konfiguration, Verwendung, Best Practice usw.

        public override string ToString() => $"{Heading}";

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

                if (customDescription != null)
                {
                    customDescriptionVM.Heading = TexReplace(customDescription.Heading);
                    customDescriptionVM.DescriptionText = TexReplace(customDescription.DescriptionText);
                    customDescriptionVM.CoverletterText = TexReplace(customDescription.CoverletterText);
                    customDescriptionVM.Notes = TexReplace(customDescription.Notes);

                    return customDescriptionVM;
                }
                else
                {
                    Debug.WriteLine($"CustomDescription für {lineItemVM.ProductNumber}#{lineItemVM.OptionNumber} nicht vorhanden! Verwende (vorläufig) Standardbeschreibung {lineItemVM.SapShortDescription}!");
                    customDescriptionVM.DescriptionText = TexReplace(lineItemVM.SapShortDescription);
                    customDescriptionVM.Heading = TexReplace(lineItemVM.SapShortDescription);
                }
                return customDescriptionVM;
            }
        }

        private static string TexReplace(string text)
        {
            text = text.Contains("&") ? text.Replace("&", "\\&") : text;
            text = text.Contains("<Shift-Enter>") ? text.Replace("<Shift-Enter>", "\\newline ") : text;

            return text;
        }
    }
}
