using Gremlin.GremlinData.DBClasses;
using Gremlin.GremlinData.EntityClasses;
using Gremlin.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Gremlin.GremlinUI.ViewModels
{
    internal class AccountVM : BaseVM
    {
        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<ContactVM> Contacts { get; set; }
        public AccountType AccountType { get; set; }
        public SubMarket SubMarket { get; set; }

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

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

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

        public static AccountVM ConvertAccountToVM(Account account)
        {
            AccountVM accountVM = new();

            accountVM.AccountType = account.AccountType;
            accountVM.SubMarket = account.SubMarket;
            accountVM.AccountName = account.AccountName;
            accountVM.Street = account.Street;
            accountVM.ZIP = account.ZIP;
            accountVM.City = account.City;
            accountVM.PhoneNumber = account.PhoneNumber;
            accountVM.FaxNumber = account.FaxNumber;
            accountVM.Webpage = account.Webpage;
            accountVM.EMail = account.EMail;
            accountVM.SAPAccountNumber = account.SAPAccountNumber;

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

            return accountVM;
        }
    }
}