using Caliburn.Micro;
using Gremlin.GremlinData.DBClasses;
using Gremlin.GremlinData.EntityClasses;
using Gremlin.MVVM.Models;
using Gremlin.MVVM.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Gremlin.MVVM
{
	internal class AccountViewModel : PropertyChangedBase
	{
		public uint SAPAccountNumber { get; set; }
		public string AccountName { get; set; }
		public string Street { get; set; }
		public uint ZIP { get; set; }
		public string City { get; set; }
		public string PhoneNumber { get; set; }
		public string FaxNumber { get; set; }
		public string Webpage { get; set; }
		public string EMail { get; set; }
		public ICollection<ContactViewModel> Contacts { get; set; }
		public AccountType AccountType { get; set; }
		public SubMarket SubMarket { get; set; }

		public static ObservableCollection<AccountViewModel> GetAllAccountsVM()
		{
			try
			{
				using (GremlinContext gremlinContext = new())
				{
					List<Account> accounts = gremlinContext.Accounts.Include(account => account.Contacts).ToList();
					ObservableCollection<AccountViewModel> accountsVM = new();

					foreach (Account account in accounts)
					{
						accountsVM.Add(ConvertAccountToVM(account));
					}

					return accountsVM;
				}
			}
			catch (Exception ex)
			{
				ErrorHandler.ShowErrorInMessageBox(ex);
				return null;
				throw;
			}
		}

		public static AccountViewModel ConvertAccountToVM(Account account)
		{
			AccountViewModel accountVM = new()
			{
				AccountType = account.AccountType,
				SubMarket = account.SubMarket,
				AccountName = account.AccountName,
				Street = account.Street,
				ZIP = account.ZIP,
				City = account.City,
				PhoneNumber = account.PhoneNumber,
				FaxNumber = account.FaxNumber,
				Webpage = account.Webpage,
				EMail = account.EMail,
				SAPAccountNumber = account.SAPAccountNumber
			};

			List<ContactViewModel> contactsVM = new();
			foreach (Contact contact in account.Contacts)
			{
				contactsVM.Add(ContactModel.ConvertContactToContactVM(contact));
			}
			accountVM.Contacts = contactsVM;

			return accountVM;
		}
	}
}