using System;
using System.Linq;
using System.Web.Mvc;
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
    {
        private readonly IRepository<vPlatnosciEcard> _repVPayment;
        private readonly IRepository<PlatnosciEcard> _repPayment; 
        private readonly FunkcjePlatnosci _funkcjePlatnosci;
        private readonly eCardData _eCardData;
        private readonly ITranslateManager _translateManager;

        public MerchantController()
        {
            _repVPayment = new Repository<vPlatnosciEcard>(new DataContext());
            _repPayment = new Repository<PlatnosciEcard>(new DataContext());
            _funkcjePlatnosci = new FunkcjePlatnosci(_repPayment);
            _translateManager = new Translation();
            _eCardData = new eCardData(_repPayment);
        }
        public MerchantController(IRepository<vPlatnosciEcard> repVPayment, IRepository<PlatnosciEcard> repPayment, ITranslateManager translate, eCardData ecardData)
        {
            _repVPayment = repVPayment;
            _repPayment = repPayment;
            _translateManager = translate;
            _funkcjePlatnosci = new FunkcjePlatnosci(_repPayment, _translateManager);            
            _eCardData = ecardData;
        }

        public ActionResult Merchant(Payer payer, string language)
        {
            language = _funkcjePlatnosci.SetLanguage(language);

            var id1 = Convert.ToInt32(payer.Id_faktury);
            var platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();

            var errorViewData = _funkcjePlatnosci.IsError(platnosc, ControllerContext.HttpContext.User.Identity.Name);
            if (!String.IsNullOrEmpty(errorViewData.Error)) 
                return View("Error1", errorViewData);

            var merchant = _eCardData.CreateMerchantData(platnosc, payer, language, Session.SessionID);
            
            if (merchant == null || (merchant != null && (!String.IsNullOrEmpty(merchant.Error))))
                return View("Error1", _funkcjePlatnosci.InitErrorViewData(_translateManager.Translate("tlumaczenia", "error_hash"), payer.Id_faktury));
            
            var adres = _eCardData.GetUrl(merchant);
            Response.Redirect(adres);           
            return new EmptyResult();          
        } 
    }
}
