using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Text.RegularExpressions;

namespace TrayCheckoutApi.Controllers
{
    public class GetTransactionController : Controller
    {

        private string tokenTransaction;
        private string xmlResponse;
        private string dataResponse;
        private string resultError;
        private string message;
        private string dataRequest;

        private void setTokenTransaction(string token_transaction)
        {
            tokenTransaction = token_transaction;
        }

        public ActionResult Index()
        {
            resultError = "";
            message = "";
            setTokenTransaction("96d5cc74a5617705ae8c564e1ca0d402");
            ViewData["token_transaction"] = "96d5cc74a5617705ae8c564e1ca0d402";
            GetTransaction();
            ViewData["xmlResponse"] = xmlResponse;
            ViewData["dataResponse"] = dataResponse;
            ViewData["dataRequest"] = dataRequest;
            messageService();
            return View();
        }

        private void formatForm(List<KeyValuePair<string, string>> form)
        {
            dataRequest = string.Join(",", form.ToArray());
            dataRequest = Regex.Replace(dataRequest, @"[,]", "\n");
        }

        private void messageService()
        {
            ViewData["messageColor"] = (resultError.Count() > 0) ? "#ff0000" : "#00ff00";
            ViewData["resultMessage"] = " Get Transaction - message_response[" + message + "]! \n" + resultError;
        }

        private List<KeyValuePair<string, string>> formData()
        {
            var list = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("token_account", ConfigTrayCheckout.tokenAccount));
            list.Add(new KeyValuePair<string, string>("token_transaction", tokenTransaction));
            return list;
        }

        private void GetTransaction()
        {
            var form = formData();
            var content = new FormUrlEncodedContent(form);
            formatForm(form); //Método pode ser excluido, utilizado apenas para quebrar linha dos dados do form para melhor visualização
            TrayCheckout tc = new TrayCheckout();
            tc.RequestTrayCheckout(content, ConfigTrayCheckout.UrlGetByToken());
            if (tc.getHttpStatusCode().Equals(HttpStatusCode.OK))
            {
                XmlDocument xml = new XmlDocument();
                xmlResponse = tc.getContent();
                xml.LoadXml(xmlResponse);
                tc.setXml(xml);
                if (!tc.sucessResponse())
                {
                    message = tc.getMessage();
                    //atribuir erros para ser exibido
                    resultError += tc.getGeneralError();
                    resultError += tc.getValidationError();
                    return;
                }
                message = tc.getMessage();
                XmlNodeList transaction = xml.GetElementsByTagName("transaction");
                dataTransaction(transaction[0]);
                XmlNodeList payment = xml.GetElementsByTagName("payment");
                dataPayment(payment[0]);
            }
        }


        private void dataPayment(XmlNode nodePayment)
        {
            string price_payment = nodePayment["price_payment"].InnerText;
            string payment_response = nodePayment["payment_response"].InnerText;
            string url_payment = nodePayment["url_payment"].InnerText;
            string tid = nodePayment["tid"].InnerText;
            string split = nodePayment["split"].InnerText;
            string payment_method_id = nodePayment["payment_method_id"].InnerText;
            string payment_method_name = nodePayment["payment_method_name"].InnerText;
            string linha_digitavel = nodePayment["price_payment"].InnerText;
            dataResponse += "\nMethod: " + payment_method_id + " - " + payment_method_name + " Split: " + split + " Price: " + price_payment;
            dataResponse += "\nResponse: " + payment_response + " \nUrl Payment:" + url_payment;
        }

        private void dataTransaction(XmlNode nodeTransaction)
        {
            string order_number = nodeTransaction["order_number"].InnerText;
            string status_id = nodeTransaction["status_id"].InnerText;
            string status_name = nodeTransaction["status_name"].InnerText;
            string transaction_id = nodeTransaction["transaction_id"].InnerText;
            dataResponse += "\nPedido: " + order_number;
            dataResponse += "\nStatus: " + status_id + " - " + status_name;
            dataResponse += "\nId Transação: " + transaction_id;
        }
    }
}
