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";
        private int ORDERNUMBER = 122;

        private string merchantId;
        private readonly PlatnosciDataContext _context;
        private readonly IRepository<PlatnosciEcard> _rep;
        private FunkcjePlatnosci _func;

        public MerchantController()
        {   
            _rep = new Repository<PlatnosciEcard>(new DataContext1());
            _context = new PlatnosciDataContext();
            _func = new FunkcjePlatnosci();
        }
        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 = _rep.FindInvoiceById(id1).SingleOrDefault();
                 
            if (platnosc == null)
            {
                ErrorViewData errorViewData = _func.InitErrorViewData(HttpContext.GetGlobalResourceObject("tlumaczenia", "brakdanych").ToString());
                return View("Error1", errorViewData);
            }
            else if (!_func.UserIdentity(platnosc, ControllerContext.HttpContext.User.Identity.Name))
            {
                ErrorViewData errorViewData = _func.InitErrorViewData(HttpContext.GetGlobalResourceObject("tlumaczenia", "weryfikacja").ToString());
                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) return View("Error");

            string hash = GetHash(newPayment, systemKs);
            hash = hash.Replace("\n","");
            if (hash == BAD_HASH  || hash == "" ) return View("Error");

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

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

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

            var merchantViewData = InitMerchantViewData(newPayment, hash, merchantId, LinkFail, LinkOk);
            wyslij(merchantViewData, hash, merchantId);
            return View(merchantViewData);            
        }
        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)
            {                
               // _rep.Insert(platnosc);
                return true;
            }
            return false;
        }
        private MerchantViewData InitMerchantViewData(PlatnosciEcard newPayment, string hash, string Id, string LinkFail, string LinkOk)
        {
            MerchantViewData merchantViewData = new MerchantViewData();
            merchantViewData.nowaPlatnosc = newPayment;
            merchantViewData.Hash = hash;
            merchantViewData.merchantId = Id;
            merchantViewData.LinkFail = LinkFail;
            merchantViewData.LinkOk = LinkOk;
            
            //wartosci testowe
            merchantViewData.nowaPlatnosc.ORDERNUMBER = ORDERNUMBER;
            merchantViewData.nowaPlatnosc.ORDERDESCRIPTION = "222";
            merchantViewData.nowaPlatnosc.AMOUNT = 300;
            merchantViewData.nowaPlatnosc.CURRENCY = "985";
            merchantViewData.nowaPlatnosc.SESSIONID = "ff";
            merchantViewData.merchantId = "171485000";
            merchantViewData.LinkFail = "";
            merchantViewData.LinkOk = "";
            return merchantViewData;
        }
        private string GetHash(PlatnosciEcard p, string ks)
        {
            string strResponse;
            /*PlatnosciEcard platnosc = _rep.FindOne(i => i.ORDERDESCRIPTION == p.ORDERDESCRIPTION && i.IDFaktury == p.IDFaktury && i.Data == p.Data);
            string adres = "https://pay.ecard.pl/servlet/HS?orderNumber="+p.ORDERNUMBER;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adres);
            string dane = "&orderDescription=&amount=" + platnosc.AMOUNT;
            dane += "&currency=" + platnosc.CURRENCY;
            if (ks == "1") dane += "&merchantId=171485000&password=ashSeth2";
                else dane += "&merchantId=170906000&password=JaYpqfs0"; */

            //dane testowe
            string adres = "https://pay.ecard.pl/servlet/HS?orderNumber="+ORDERNUMBER;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adres);
            string dane = "&orderDescription=&amount=300&currency=985&merchantId=171485000&password=ashSeth2";                
            
            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(MerchantViewData m, string hash, string id)
        {
            string adres = "https://pay.ecard.pl/servlet/PSTEST?ORDERDESCRIPTION="+m.nowaPlatnosc.ORDERDESCRIPTION;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adres);
            string dane = "&AMOUNT=300&CURRENCY=985&ORDERNUMBER="+ORDERNUMBER+"&NAME="+m.nowaPlatnosc.NAME+"&SURNAME="+m.nowaPlatnosc.SURNAME+"&LANGUAGE=PL&CHARSET=ISO-8859-2";
            dane += "&COUNTRY=616&PAYMENTTYPE=CARDS&JS=1&HASH=" + hash + "&MERCHANTID=171485000&AUTODEPOSIT=" + m.nowaPlatnosc.AUTODEPOSIT + "&LINKFAIL=";
            dane += "&LINKOK=&SESSIONID=";
            Response.Redirect(adres + dane);
        }
    }
}
