using System;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.UI;

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Collections.Generic;
using Platnosci.Models;
using Platnosci.Core.Linq;
using Platnosci.Core.Interface;
using System.Configuration;
using System.Net;
using System.IO;
using System.Threading;

namespace Platnosci.Controllers
{
    [Authorize]
    public class MerchantController : Controller
    {
        public const string BAD_HASH = "zlyHash";       //błędne hasło - odpowied z eCard
        public const string CARDS = "CARDS";            //obsługa tylko kart płatniczych
        public const string KOD_POLSKA = "616";         //kod kraju Akceptanta - Polska
        public const string KODOWANIE = "ISO-8859-2";
        public const string HASH_ERROR_INFO = "payment not exist";
        private string merchantId;

        private readonly IRepository<vPlatnosciEcard> _repVPayment;
        private readonly IRepository<PlatnosciEcard> _repPayment; 
        private FunkcjePlatnosci _func;
        private ITranslateManager _t;

        public MerchantController()
        {
            _repVPayment = new Repository<vPlatnosciEcard>(new DataContext1());
            _repPayment = new Repository<PlatnosciEcard>(new DataContext1());
            _func = new FunkcjePlatnosci();
            _t = new Translation();
        }
        public ActionResult Merchant(Payer payer, string language)
        {
            System.Diagnostics.Debug.WriteLine("MerchantController:Merchant:" + language);
            language = _func.setLanguage(language);

            int id1 = Convert.ToInt32(payer.Id_faktury);
            vPlatnosciEcard platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
                 
            if (platnosc == null)
            {
                ErrorViewData errorViewData = _func.InitErrorViewData(_t.Translate("tlumaczenia", "brakdanych"));
                return View("Error1", errorViewData);
            }
            else if (!_func.UserIdentity(platnosc, ControllerContext.HttpContext.User.Identity.Name))
            {
                ErrorViewData errorViewData = _func.InitErrorViewData(_t.Translate("tlumaczenia", "weryfikacja"));
                return View("Error1", errorViewData);
            }
            
            Waluta waluta = _func.setAmount(platnosc);
            var newPayment = InitNewPayment(id1, platnosc, waluta, payer );            

            string systemKs = platnosc.SystemKsiegowyId.ToString();

            bool createPayment = AddNewPayment(newPayment);
            if (createPayment == false)
            {
                ErrorViewData errorViewData = _func.InitErrorViewData(_t.Translate("tlumaczenia", "error_hash"));
                errorViewData.idfaktury = payer.Id_faktury;
                return View("Error1", errorViewData);
            }

            string hash = GetHash(newPayment, systemKs);
            hash = hash.Replace("\n","");
            if (hash == BAD_HASH || hash == "" || hash == HASH_ERROR_INFO)
            {
                ErrorViewData errorViewData = _func.InitErrorViewData(_t.Translate("tlumaczenia", "error_hash"));
                errorViewData.idfaktury = payer.Id_faktury;
                return View("Error1", errorViewData);
            }

            if (systemKs == "1") merchantId = "170906000";
                else merchantId = "171485000";

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

            string LinkFail = ConfigurationManager.AppSettings["Strona"];
            LinkFail += "/" + language + ConfigurationManager.AppSettings["LinkFail"];
            LinkFail += "/" + newPayment.IDFaktury + "?o=" + orderek;

            string LinkOk = ConfigurationManager.AppSettings["Strona"];
            LinkOk += "/" + language + ConfigurationManager.AppSettings["LinkOk"];
            LinkOk += "/" + newPayment.IDFaktury + "?o=" + orderek; ;

            //merchantid dla srodowiska testowego
            merchantId = "171485000";
            wyslij(newPayment, hash, merchantId, LinkFail, LinkOk);
            return new EmptyResult();          
        }
        private PlatnosciEcard InitNewPayment(int id, vPlatnosciEcard platnosc, Waluta waluta, Payer payer)
        {
            PlatnosciEcard newPayment = new PlatnosciEcard();
            newPayment.IDFaktury = id;
            newPayment.ORDERDESCRIPTION = platnosc.Faktura_Numer;
            newPayment.nip = platnosc.nip;
            newPayment.nrZlecenia = "";
            newPayment.AMOUNT = waluta.Amount;
            newPayment.CURRENCY = waluta.Currency;
            newPayment.SESSIONID = Session.SessionID;
            newPayment.NAME = payer.FirstName;
            newPayment.SURNAME = payer.LastName;
            newPayment.AUTODEPOSIT = true;
            newPayment.LANGUAGE = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpper(); 
            newPayment.CHARSET = KODOWANIE;
            newPayment.COUNTRY = KOD_POLSKA;
            newPayment.JS = true;
            newPayment.PAYMENTTYPE = CARDS;
            newPayment.Data = DateTime.Now;
            newPayment.Status = null;
            newPayment.Status_data = null;
            return newPayment;
        }
        private bool AddNewPayment(PlatnosciEcard platnosc)
        {
            if (platnosc != null)
            {                
                _repPayment.Insert(platnosc);
                return true;
            }
            return false;
        }
        private string GetHash(PlatnosciEcard p, string ks)
        {
            string strResponse;
            PlatnosciEcard platnosc = _repPayment.Find(i => i.ORDERDESCRIPTION == p.ORDERDESCRIPTION && i.IDFaktury == p.IDFaktury && i.Data == p.Data).First();

            if (platnosc == null) return HASH_ERROR_INFO;

            string adres = "https://pay.ecard.pl/servlet/HS?orderNumber=" + platnosc.ORDERNUMBER;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adres);
            string dane = "&orderDescription=&amount=" + platnosc.AMOUNT;
            dane += "&currency=" + platnosc.CURRENCY;
            dane += "&merchantId=171485000&password=ashSeth2";

          //  if (ks == "1") dane += "&merchantId=171485000&password=ashSeth2";
            //    else dane += "&merchantId=170906000&password=JaYpqfs0";

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

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

            StreamReader streamResponse = new StreamReader(req.GetResponse().GetResponseStream());
            strResponse = streamResponse.ReadToEnd();
            streamResponse.Close();
                     
            return strResponse;
        }
        private void wyslij(PlatnosciEcard m, string hash, string merchantid, string linkok, string linkfail)
        {
            //string adres = "https://pay.ecard.pl/payment/PS?ORDERDESCRIPTION=" + m.ORDERDESCRIPTION;
            
            string adres = "https://pay.ecard.pl/servlet/PSTEST?ORDERDESCRIPTION=" + m.ORDERDESCRIPTION;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adres);
            string dane = "&AMOUNT=" + m.AMOUNT + "&CURRENCY=" + m.CURRENCY + "&ORDERNUMBER=" + m.ORDERNUMBER;
            dane += "&NAME=" + m.NAME + "&SURNAME=" + m.SURNAME + "&LANGUAGE=" + m.LANGUAGE + "&CHARSET=ISO-8859-2";
            dane += "&COUNTRY=616&PAYMENTTYPE=CARDS&JS=1&HASH=" + hash + "&MERCHANTID=" + merchantid + "&AUTODEPOSIT=" + m.AUTODEPOSIT;
            dane += "&LINKFAIL=" + linkfail + "&LINKOK=" + linkok + "&SESSIONID=" + m.SESSIONID;
            Response.Redirect(adres + dane);
        }
    }
}
