using Microsoft.AspNet.WebHooks;
using System;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using EKONO.LN;

namespace WebhookZunify
{
    public class ZunifyReceiver : WebHookHandler
    {
        private Logica logica;
        
        public ZunifyReceiver()
        {
            this.Receiver = "genericjson";
        }
        public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)
        {
            //Request
            object result;
            string response;
            HttpResponseMessage res = new HttpResponseMessage();
            logica = new Logica();
            try {
                dynamic data = context.Data.ToString();
                ZunifyWebhookObject zwo = JsonConvert.DeserializeObject<ZunifyWebhookObject>(data);
                string dbresponse = logica.Add_ZunifyWHRegister(zwo.transactionId, zwo.chargeCode, zwo.amount, zwo.discount, zwo.currency, zwo.terminalCode);
                if (String.IsNullOrEmpty(dbresponse))
                {
                    logica.Add_ZunifyLog("0","WEBHOOK INPUT IdTransaccion: " + zwo.transactionId + " Codigo Cargo: " + zwo.chargeCode + " Terminal: " + zwo.terminalCode + " Cargo: " + zwo.amount + " Descuento: " + zwo.discount);
                    result = new { sucess = true };
                    res.StatusCode = HttpStatusCode.Accepted;
                }
                else
                {
                    logica.Add_ZunifyLog("-1","WEBHOOK DB ERROR: " + dbresponse);
                    result = new { sucess = false };
                    res.StatusCode = HttpStatusCode.NotAcceptable;
                }
                
            }
            catch (Exception e) {
                logica.Add_ZunifyLog("-5","WEBHOOK INPUT IdTransaccion: " + e.Message + " Formato no valido");
                result = new { sucess = false, message = "Formato no valido" };
                res.StatusCode = HttpStatusCode.NotAcceptable;
            }
            //Response  
            response = JsonConvert.SerializeObject(result);
            res.Content = new StringContent(response, System.Text.Encoding.UTF8, "application/json");
            context.Response = res;
            return Task.FromResult(true);
        }
    }

    public class ZunifyWebhookObject
    {
        public string transactionId { get; set; }
        public DateTime date { get; set; }
        public string chargeCode { get; set; }
        public decimal amount { get; set; }
        public decimal discount { get; set; }
        public string currency { get; set; }
        public string terminalCode { get; set; }

    }
}