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

namespace SFI.COMM.LIB.Redis
{
    public class TransferAction<T> : ITransferAction, IDisposable
    {
        public string CommandKey { get; set; }
        public Action<TransferResult<T>> ResultAction { get; set; }
         
        public void RunResult(string data)
        {
            if (this.ResultAction == null)
                return;

            TransferResult<T> result = null;

            if (!string.IsNullOrEmpty(data))
            {
                try
                {
                    if (typeof(T).ToString().ToLower().Contains("string")) 
                        result = new TransferResult<T>() { Success = true, Data = (T)(object)data };
                    else
                        result = JsonConvert.DeserializeObject<TransferResult<T>>(data);
                }
                catch (Exception exs)
                {
                    result = new TransferResult<T>() { Success = false, Message = "Tip donusumlerinde hata var!" };
                }
            }

            _ = Task.Run(() => ((Action<TransferResult<T>>)this.ResultAction.Clone())(result));

            Commander.TransferActionList.Remove(this);
            this.Dispose();
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

    }
}
