using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Synchronization
{
    // Listing 17-10
    public class SaleLog
    {
        private readonly object _sync = new object();

        private decimal _total;

        private readonly List<string> _saleDetails = new List<string>();

        public decimal Total
        {
            get
            {
                lock (_sync)
                {
                    return _total;
                }
            }
        }

        public void AddSale(string item, decimal price)
        {
            string details = string.Format("{0} sprzedano za {1}", item, price);
            lock (_sync)
            {
                _total += price;
                _saleDetails.Add(details);
            }
        }

        public string[] GetDetails(out decimal total)
        {
            lock (_sync)
            {
                total = _total;
                return _saleDetails.ToArray();
            }
        }

        public string[] ExpandedLockCode(out decimal total)
        {
            // Listing 17-11
            bool lockWasTaken = false;
            var temp = _sync;
            try
            {
                Monitor.Enter(temp, ref lockWasTaken);
                {
                    total = _total;
                    return _saleDetails.ToArray();
                }
            }
            finally
            {
                if (lockWasTaken)
                {
                    Monitor.Exit(temp);
                }
            }

        }
    }
}
