using System;
using System.Linq;
using System.Web.Mvc;
using Platnosci.Models;
using Platnosci.Core.Linq;
using Platnosci.Core.Interface;

namespace Platnosci.Controllers
{
    
    [Authorize]
    public class PlatnoscController : Controller
    {
        public const string ISPAID = "payment_deposited";       //transakcja potwierdzona do rozliczenia
        private readonly IRepository<vPlatnosciEcard> _repVPayment;       
        private readonly IRepository<PlatnosciEcard> _repPayment;
        private readonly IRepository<PotwierdzeniaEcard> _repConfirm;
        private readonly ITranslateManager _translateManager;
        private readonly FunkcjePlatnosci _funkcjePlatnosci;
              
        public PlatnoscController()
        {
            _repVPayment = new Repository<vPlatnosciEcard>(new DataContext());
            _repPayment = new Repository<PlatnosciEcard>(new DataContext());
            _repConfirm = new Repository<PotwierdzeniaEcard>(new DataContext());
            _funkcjePlatnosci = new FunkcjePlatnosci();
            _translateManager = new Translation();         
        }
        public PlatnoscController(IRepository<vPlatnosciEcard> repVPayment, IRepository<PlatnosciEcard> repPayment, IRepository<PotwierdzeniaEcard> repConfirm, ITranslateManager translate)
        {
            _repVPayment = repVPayment;
            _repPayment = repPayment;
            _repConfirm = repConfirm;
            _funkcjePlatnosci = new FunkcjePlatnosci();
            _translateManager = translate;
        }
        public ActionResult Show(string id, string language)
        {
            language = _funkcjePlatnosci.setLanguage(language);
            var id1 = ConvertId(id);

            var platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
            if (!String.IsNullOrEmpty(IsError(platnosc).Error)) return View("Error1", IsError(platnosc));

            var kwota = _funkcjePlatnosci.BruttoToString(platnosc.Brutto, platnosc.waluta_brutto, platnosc.waluta_miano);
            
            var payer = InitPayer(platnosc.ID_faktury);
            
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, payer, "", kwota);  

            var tablicaPotwierdzenia = _repConfirm.FindItemsByIdFaktury(id1);
            if (tablicaPotwierdzenia.Count > 0) //platnosc za fakture zostala uregulowana
            {
                var dataZaplaty = String.Format("{0:dd-MM-yyyy}", tablicaPotwierdzenia[0].AUTHTIME);
                invoiceDeatailsViewData.info = String.Format(_translateManager.Translate("tlumaczenia","zaplacono"), platnosc.Faktura_Numer, dataZaplaty);
                invoiceDeatailsViewData.termin = dataZaplaty;
                return View("Paid", invoiceDeatailsViewData);
            }       
            return View(invoiceDeatailsViewData);            
        }        
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Show(Payer payer, string language)
        {
            language = _funkcjePlatnosci.setLanguage(language);
            
            var platnosc = _repVPayment.Find(p => p.ID_faktury == payer.Id_faktury).SingleOrDefault();
            
            if (!String.IsNullOrEmpty(IsError(platnosc).Error)) return View("Error1", IsError(platnosc));
            
            if (String.IsNullOrEmpty(payer.FirstName))
            {
                ModelState.AddModelError("Payer.FirstName", _translateManager.Translate("tlumaczenia", "err_imieWK"));
            }
            if (String.IsNullOrEmpty(payer.LastName))
            {
                ModelState.AddModelError("Payer.LastName", _translateManager.Translate("tlumaczenia", "err_nazwiskoWK"));
            }
            if (ModelState.IsValid == false)
            {
                var kwota = _funkcjePlatnosci.BruttoToString(platnosc.Brutto, platnosc.waluta_brutto, platnosc.waluta_miano); 
                var viewData = InitInvoiceDetailsViewData(platnosc, payer, "", kwota );
                return View("Show",viewData); 
            }

            return RedirectToAction("Merchant", "Merchant", payer);
        }

        public ActionResult Ok(string id, string language, string o)
        {
            var order = ConvertId(o);
            
            language = _funkcjePlatnosci.setLanguage(language);
            
            var id1 = ConvertId(id);
            
            var platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
            
            if (!String.IsNullOrEmpty(IsError(platnosc).Error)) return View("Error1", IsError(platnosc));            
            
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, null, "" , "");

            //sprawdzamy czy dla kombinacji ordernumber i idfaktury istnieje platnosc,
            //jesli tak, to sprawdzamy czy przyszlo potwierdzenie z eCardu.             
            if (order > 0)
                if (CheckConfirm(id1, order) == 0)   //nie ma potwierdzenia z eCardu
                    invoiceDeatailsViewData.info = String.Format(_translateManager.Translate("tlumaczenia", "blad1"), invoiceDeatailsViewData.vPlatnosciEcard.Faktura_Numer);
                
            if (order == 0 || (CheckConfirm(id1, order) == 2) && order > 0 )
                invoiceDeatailsViewData.info = _translateManager.Translate("tlumaczenia", "weryfikacja");
           
            return View(invoiceDeatailsViewData);
        }
        public ActionResult Fail(string id, string language)
        {
            language = _funkcjePlatnosci.setLanguage(language);
            var id1 = ConvertId(id);
            var platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
            if (!String.IsNullOrEmpty(IsError(platnosc).Error)) return View("Error1", IsError(platnosc));

            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, null, "", "");
            return View(invoiceDeatailsViewData);
        }
        public ActionResult Form()
        {
            return View();
        }
        public ActionResult Status()
        {
            var potwierdzenie = new PotwierdzeniaEcard();
            var content = new ContentResult();
            try
            {
                if (!String.IsNullOrEmpty(Request.Form["APPROVALCODE"])) potwierdzenie.APPROVALCODE = Request.Form["APPROVALCODE"];
                if (!String.IsNullOrEmpty(Request.Form["AUTHTIME"])) potwierdzenie.AUTHTIME = Convert.ToDateTime(Request.Form["AUTHTIME"]);
                if (!String.IsNullOrEmpty(Request.Form["BIN"])) potwierdzenie.BIN = Request.Form["BIN"];
                if (!String.IsNullOrEmpty(Request.Form["COMMTYPE"])) potwierdzenie.COMMTYPE = Request.Form["COMMTYPE"];
                if (!String.IsNullOrEmpty(Request.Form["CURRENTSTATE"])) potwierdzenie.CURRENTSTATE = Request.Form["CURRENTSTATE"];
                if (!String.IsNullOrEmpty(Request.Form["DATATRANSMISJI"])) potwierdzenie.DATATRANSMISJI = Convert.ToDateTime(Request.Form["DATATRANSMISJI"]);
                if (!String.IsNullOrEmpty(Request.Form["EVENTTYPE"])) potwierdzenie.EVENTTYPE = Convert.ToBoolean(Request.Form["EVENTTYPE"]);
                if (!String.IsNullOrEmpty(Request.Form["MERCHANTNUMBER"])) potwierdzenie.MERCHANTNUMBER = Request.Form["MERCHANTNUMBER"];
                if (!String.IsNullOrEmpty(Request.Form["ORDERNUMBER"])) potwierdzenie.ORDERNUMBER = Convert.ToInt32(Request.Form["ORDERNUMBER"]);
                if (!String.IsNullOrEmpty(Request.Form["PAYMENTNUMBER"])) potwierdzenie.PAYMENTNUMBER = Convert.ToBoolean(Request.Form["PAYMENTNUMBER"]);
                if (!String.IsNullOrEmpty(Request.Form["PAYMENTTYPE"])) potwierdzenie.PAYMENTTYPE = Convert.ToBoolean(Request.Form["PAYMENTTYPE"]);
                if (!String.IsNullOrEmpty(Request.Form["PREVIOUSSTATE"])) potwierdzenie.PREVIOUSSTATE = Request.Form["PREVIOUSSTATE"];
                if (!String.IsNullOrEmpty(Request.Form["TYPE"])) potwierdzenie.TYPE = Request.Form["TYPE"];
                if (!String.IsNullOrEmpty(Request.Form["VALIDATIONCODE"])) potwierdzenie.VALIDATIONCODE = Request.Form["VALIDATIONCODE"];
                if (!String.IsNullOrEmpty(Request.Form["WITHCVC"])) potwierdzenie.WITHCVC = Request.Form["WITHCVC"];

                _repConfirm.Insert(potwierdzenie);

                if (potwierdzenie.ORDERNUMBER.HasValue)
                    UpdateStatus(potwierdzenie.ORDERNUMBER.Value, potwierdzenie.CURRENTSTATE);

                content.Content = "OK";                
            }
            catch(Exception ex)
            {
                content.Content = "FALSE " + ex.Message + " " + ex.GetType();
            }       
            
            return content;
        }

        private static Payer InitPayer(int idFaktury)
        {
            var payer = new Payer {Id_faktury = idFaktury};
            return payer;
        }

        private static InvoiceDetailsViewData InitInvoiceDetailsViewData(vPlatnosciEcard platnosc, Payer payer, string status, string brutto )
        {
            var invoiceDeatailsViewData = new InvoiceDetailsViewData();
            invoiceDeatailsViewData.vPlatnosciEcard = platnosc;
            invoiceDeatailsViewData.Payer = payer;
            invoiceDeatailsViewData.Status = status;
            invoiceDeatailsViewData.brutto = brutto;
            return invoiceDeatailsViewData;
        }

        public int ConvertId(string id)
        {
            int id1;
            return Int32.TryParse(id, out id1) ? id1 : 0;
        }

        public ErrorViewData IsError(vPlatnosciEcard platnosc)
        {
            var errortxt = "";
            
            if (platnosc == null) 
                errortxt = _translateManager.Translate("tlumaczenia", "brakdanych");
            else if (!_funkcjePlatnosci.UserIdentity(platnosc, HttpContext.User.Identity.Name)) 
                errortxt = _translateManager.Translate("tlumaczenia","weryfikacja");

            return _funkcjePlatnosci.InitErrorViewData(errortxt,0);
        }

        public void UpdateStatus(int ordernumber, string currentstate)
        {
            var platnosc = _repPayment.Find(p => p.ORDERNUMBER == ordernumber).SingleOrDefault();

            if (platnosc == null || currentstate != ISPAID) return;

            platnosc.Status = true;
            platnosc.Status_data = DateTime.Now;
            _repPayment.SubmitChanges();
        }

        public int CheckConfirm(int idfaktury, int order)
        {
            var pl = _repPayment.Find(p => p.ORDERNUMBER == order && p.IDFaktury == idfaktury).SingleOrDefault();

            if (pl != null)
            {
                var confirm = _repConfirm.Find(p => p.ORDERNUMBER == order).FirstOrDefault();
                if (confirm == null) return 0; //potwierdzenie nie przyszlo z eCardu
            }
            else
            {
                return 2; //nie ma platnosci o takim idfaktury i ordernumber
            }
            
            return 1;    //potwierdzenie przyszlo z eCardu
        }  
    }
}
