using System.Collections.ObjectModel;
using MvcKendoUiSample.Models;
using System.Collections.Generic;
using System.Linq;

internal static class DataSource
{
    private static object _mutex = new object();
    private static Collection<Customer> _customers = null;

    internal static Collection<Customer> Customers
    {
        get
        {
            if (_customers == null)
            {
                lock (_mutex)
                {
                    if (_customers == null)
                    {
                        LoadData();
                    }
                }
            }

            return _customers;
        }
    }

    private static void LoadData()
    {
        _customers = new Collection<Customer>();

        var customer = new Customer
                            {
                                AccountNumber = "00001",
                                Id = "1",
                                Name = "Wayne Enterprises",
                                Status = Status.Active
                            };

        customer.Adresses.Add(new Address
                                   {
                                       Id = 1,
                                       Name = "Main Address",
                                       StreetLine1 = "Wayne Plaza",
                                       StreetLine2 = string.Empty,
                                       City = "Gotham City",
                                       Type = AddressType.Billing
                                   });

        _customers.Add(customer);
    }

    internal static void Store(Customer customer)
    {
        lock(_mutex)
        {
            var previousItem = Customers.Where(c=>c.Id == customer.Id).FirstOrDefault();

            if (previousItem != null)
            {
                Customers.Remove(previousItem);
            }
            else
            {
                customer.Id = (int.Parse(Customers.Max(c => c.Id)) + 1).ToString();
            }

            Customers.Add(customer);
        }
    }
}