using System;
using System.Net;
using System.IO;
using System.Linq;
using System.Configuration;
using adMoto.Payments.Core;
using adMoto.Payments.Core.Data;
using adMoto.Payments.Core.Interfaces;

namespace adMoto.Payments.Web.Models
{
    public class MerchantHelper
    {
        public const string HASH_ERROR_INFO = "payment not exist";
        private readonly PaymentsUtils _paymentsUtils;
        private IRepository<PlatnosciEcard> _repPayment;

        public MerchantHelper(IRepository<PlatnosciEcard> repPayment)
        {
            _repPayment = repPayment;
            _paymentsUtils = new PaymentsUtils(_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(Invoice invoice, Payer payer, string lang, string sessionId)
        {
            var merchant = new Merchant();

            var waluta = _paymentsUtils.SetAmount(invoice);
            var newPayment = _paymentsUtils.CreateAndAddNewPyment(invoice, waluta, payer, sessionId);

            merchant.SystemKsiegowy = invoice.SystemKsiegowyId.ToString();

#if DEBUG
            //TODO: find better method to set SystemKsiegowy when testing or developing
            merchant.SystemKsiegowy = "2";
#endif

            merchant.Payment = newPayment;
            GetMerchantInfo(merchant);
            merchant.Hash = 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 + "/?";

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

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

            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";
            }
        }
        public string SetHash(Merchant merchant)
        {
            if (merchant == null)
                throw new ArgumentNullException("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.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;
            }
            return merchant.Hash;
        }
    }
}