using System;
using System.Web;
using System.Net;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Configuration;
using Platnosci.Core.Linq;
using Platnosci.Core.Interface;

namespace Platnosci.Models
{
    public class eCardData
    {
        public const string HASH_ERROR_INFO = "payment not exist";
        private readonly FunkcjePlatnosci _funkcjePlatnosci;
        private IRepository<PlatnosciEcard> _repPayment;
        
        public eCardData(IRepository<PlatnosciEcard> repPayment)
        {
            _repPayment = repPayment;
            _funkcjePlatnosci = new FunkcjePlatnosci(_repPayment);
        }

        public String GetUrl(Merchant merchant)
        {
            if (merchant == null) 
                throw new ArgumentNullException("merchant");
            
            var dane = ConfigurationManager.AppSettings["eCard.Url"] + "?ORDERDESCRIPTION=" + merchant.Payment.ORDERDESCRIPTION;
            dane += "&AMOUNT=" + merchant.Payment.AMOUNT + "&CURRENCY=" + merchant.Payment.CURRENCY;
            dane += "&ORDERNUMBER=" + merchant.Payment.ORDERNUMBER;
            dane += "&NAME=" + merchant.Payment.NAME + "&SURNAME=" + merchant.Payment.SURNAME;
            dane += "&LANGUAGE=" + merchant.Payment.LANGUAGE + "&CHARSET=ISO-8859-2";
            dane += "&COUNTRY=616&PAYMENTTYPE=CARDS&JS=1&HASH=" + merchant.Hash;
            dane += "&MERCHANTID=" + merchant.Id + "&AUTODEPOSIT=" + merchant.Payment.AUTODEPOSIT;
            dane += "&LINKFAIL=" + merchant.LinkFail + "&LINKOK=" + merchant.LinkOk;
            dane += "&SESSIONID=" + merchant.Payment.SESSIONID;
            return dane;
        }
        public Merchant CreateMerchantData(vPlatnosciEcard invoice, Payer payer, string lang, string sessionId)
        {
            var merchant = new Merchant();
           
            var waluta = _funkcjePlatnosci.SetAmount(invoice);
            var newPayment = _funkcjePlatnosci.CreateAndAddNewPyment(invoice, waluta, payer, sessionId);

            merchant.SystemKsiegowy = invoice.SystemKsiegowyId.ToString();
            if (ConfigurationManager.AppSettings["wersja"] == "TEST")
                merchant.SystemKsiegowy = "2";

            merchant.Payment = newPayment;
            getMerchantInfo(merchant);
            SetHash(merchant);

            //przeslanie w linku ordernumber potrzebnego do wyswietlenia potwierdzenia
            var orderek = _repPayment.GetOrdernumber(newPayment.ORDERDESCRIPTION, newPayment.IDFaktury, newPayment.Data);

            var linkFail = ConfigurationManager.AppSettings["Strona"];
            linkFail += "/" + lang + ConfigurationManager.AppSettings["LinkFail"];
            linkFail += "/" + newPayment.IDFaktury + "?o=" + orderek;

            var linkOk = ConfigurationManager.AppSettings["Strona"];
            linkOk += "/" + lang + ConfigurationManager.AppSettings["LinkOk"];
            linkOk += "/" + newPayment.IDFaktury + "?o=" + orderek;

            merchant.LinkOk = linkOk;
            merchant.LinkFail = linkFail;

            if (merchant != null) merchant.IsValid();

            return merchant;
        }
        public void getMerchantInfo(Merchant merchant)
        {
            if (merchant.SystemKsiegowy == "2")
            {
                merchant.Id = "171485000";
                merchant.Password = "ashSeth2";
            }
            else
            {
                merchant.Id = "170906000";
                merchant.Password = "JaYpqfs0";
            }
        }
        private void SetHash(Merchant merchant)
        {
            var platnosc = _repPayment.Find(i => i.ORDERDESCRIPTION == merchant.Payment.ORDERDESCRIPTION && i.IDFaktury == merchant.Payment.IDFaktury && i.Data == merchant.Payment.Data).SingleOrDefault();

            if (platnosc == null || merchant == null)
            {
                merchant.Hash = HASH_ERROR_INFO;
            }
            else
            {
                var adres = "https://pay.ecard.pl/servlet/HS?orderNumber=" + platnosc.ORDERNUMBER;
                var req = (HttpWebRequest)WebRequest.Create(adres);
                var dane = "&orderDescription=&amount=" + platnosc.AMOUNT;
                dane += "&currency=" + platnosc.CURRENCY;
                dane += string.Format("&merchantId={0}&password={1}", merchant.Id, merchant.Password);

                var bdata = System.Text.Encoding.ASCII.GetBytes(dane);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = dane.Length;

                var reqStream = req.GetRequestStream();
                reqStream.Write(bdata, 0, bdata.Length);
                reqStream.Close();

                var streamResponse = new StreamReader(req.GetResponse().GetResponseStream());
                string strResponse = streamResponse.ReadToEnd();
                streamResponse.Close();
                strResponse = strResponse.Replace("\n", "");

                merchant.Hash = strResponse;
            }
        }
    }
}
