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

namespace IACommService4CSharp
{
    public abstract class IWriteCompleteCallback_t : IWriteCompleteCallback4CSharp
    {
        private Dictionary<uint, string[]> m_requestCache;
        private Mutex m_cacheMutex = new Mutex();
        public IWriteCompleteCallback_t()
        {
            m_requestCache = new Dictionary<uint, string[]>();
        }
        ~IWriteCompleteCallback_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 WriteComplete(uint transactionId, uint[] results)
        {
            var address_list = new List<string>();

            if (RetrieveAddressList(transactionId, ref address_list))
            {
                WriteComplete(address_list.ToArray(), results);
            }
        }
        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 WriteComplete(string[] addresses, uint[] results);
    }
}
