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 string merchantId;
        private readonly PlatnosciDataContext _context;
        private readonly IRepositoryPE _rep;
        private FunkcjePlatnosci _func;

        public MerchantController()
        {   
            _rep = new RepositoryPlatnosciEcard();
            _context = new PlatnosciDataContext();
            _func = new FunkcjePlatnosci();
        }
        public ActionResult Merchant(Payer payer, string language)
        {
            language = _func.setLanguage(language);

            int id1 = Convert.ToInt32(payer.Id_faktury);
            vPlatnosciEcard platnosc = _context.FindInvoiceById(id1).SingleOrDefault();
            
            if (!_func.UserIdentity(platnosc, ControllerContext.HttpContext.User.Identity.Name))
            {
                ErrorViewData errorViewData = new ErrorViewData();
                errorViewData.error = 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"); //nie można połączyć się z serverem płatności. Proszę spróbować jeszcze raz.
            }
            if (platnosc.SystemKsiegowyId == 1)
                merchantId = "170906000";
            else
                merchantId = "171485000";

            string link = ConfigurationManager.AppSettings["StatusLink"];
            string LinkFail = link + "?status=fail";
            string LinkOk = link + "?status=ok";

            var merchantViewData = InitMerchantViewData(newPayment, hash, merchantId, LinkFail, LinkOk);
            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(); //"PL";
            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 = 4;
            merchantViewData.nowaPlatnosc.ORDERDESCRIPTION = "22";
            merchantViewData.nowaPlatnosc.AMOUNT = 300;
            merchantViewData.nowaPlatnosc.CURRENCY = "985";
            merchantViewData.nowaPlatnosc.SESSIONID = "";
            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=4";
            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;
        }               
    }
}
