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 SplitCardController : Controller
    {
        private string xmlResponse;
        private string dataResponse;
        private string dataRequest;
        private string resultError;
        private string message;

        public ActionResult Index()
        {
            resultError = "";
            message = "";
            SplitCard();
            ViewData["xmlResponse"] = xmlResponse;
            ViewData["dataResponse"] = dataResponse;
            ViewData["dataRequest"] = dataRequest;
            messageService();
            return View();
        }

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

        private void SplitCard()
        {
            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.UrlSplit());
            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 splits = xml.GetElementsByTagName("splitting");
                dataSplit(splits);
            }
        }

        private void dataSplit(XmlNodeList splits)
        {
            foreach (XmlNode spl in splits)
            {
                string split = spl["split"].InnerText;
                string value_split = spl["value_split"].InnerText;
                string value_transaction = spl["value_transaction"].InnerText;
                string addition_retention = spl["addition_retention"].InnerText;
                string split_rate = spl["split_rate"].InnerText;
                string price_seller = spl["price_seller"].InnerText;
                string retention_value = spl["retention_value"].InnerText;
                dataResponse += "\n\nParcela: " + split + "x - R$" + value_split;
                dataResponse += "\nValor da Transação: " + value_transaction;
                dataResponse += "\nAddition_retention: " + addition_retention;
                dataResponse += "\nSplit_rate: " + split_rate;
                dataResponse += "\nValor Loja: " + price_seller;
                dataResponse += "\nRetenção TrayCheckout: " + retention_value;
            }
        }

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

        private static 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>("payment_method_id", "3"));
            list.Add(new KeyValuePair<string, string>("price", "100.00"));
            list.Add(new KeyValuePair<string, string>("splits[][split_transaction]", "1"));
            list.Add(new KeyValuePair<string, string>("splits[][percentage]", "0"));
            return list;
        }

    }
}
