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

namespace IACommService4CSharp
{
    public abstract class IReadCompleteCallback_t  : IReadCompleteCallback4CSharp
    {
        private Dictionary<uint, string[]> m_requestCache;
        private Mutex m_cacheMutex = new Mutex();

        public IReadCompleteCallback_t()
        {
            m_requestCache = new Dictionary<uint, string[]>();
        }
        ~IReadCompleteCallback_t()
        {
            m_requestCache.Clear();
        }
        //Internal use
        public void AddRequestCache(uint transactionId, string[] addressList)
        {
            m_requestCache[transactionId] = addressList;
        }
        public void Lock() { m_cacheMutex.WaitOne(); }
        public void Unlock() { m_cacheMutex.ReleaseMutex(); }
        //Internal use
        public override void ReadComplete(uint transactionId, IDataItem4CSharp[] dataItems)
        {
            var address_list = new List<string>();

            if(RetrieveAddressList(transactionId, ref address_list))
            {
                List<DataItem_t> dataItemList = new List<DataItem_t>();

                for (int index = 0; index < dataItems.Length; index++)
                {
                    dataItemList.Add(new DataItem_t(dataItems[index]));
                }

                ReadComplete(address_list.ToArray(), dataItemList.ToArray());
            }
        }
        private bool RetrieveAddressList(uint transactionId, ref List<string> address_list)
        {
            Lock();
            bool bFind = false;

            if (m_requestCache.ContainsKey(transactionId))
            {
                address_list = m_requestCache[transactionId].ToList();
                m_requestCache.Remove(transactionId);
                bFind = true;
            }

            Unlock();
            return bFind;
        }
        public abstract void ReadComplete(string[] addresses, DataItem_t[] dataItems);
    }
}
