using System;
using System.Linq;
using System.Web.Mvc;
using adMoto.Payments.Core;
using adMoto.Payments.Core.Data;
using adMoto.Payments.Core.Interfaces;
using adMoto.Payments.Web.Models;

namespace adMoto.Payments.Web.Controllers
{
    [Authorize]
    public class MerchantController : Controller
    {
        private readonly IRepository<Invoice> _repVPayment;
        private readonly IRepository<PlatnosciEcard> _repPayment; 
        private readonly PaymentsUtils _paymentsUtils;
        private readonly MerchantHelper _merchantHelper;
        private readonly ITranslateManager _translateManager;

        public MerchantController()
        {
            _repVPayment = new Repository<Invoice>(new DataContext());
            _repPayment = new Repository<PlatnosciEcard>(new DataContext());
            _paymentsUtils = new PaymentsUtils(_repPayment);
            _translateManager = new Translation();
            _merchantHelper = new MerchantHelper(_repPayment);
        }
        public MerchantController(IRepository<Invoice> repVPayment, IRepository<PlatnosciEcard> repPayment, ITranslateManager translate)
        {
            _repVPayment = repVPayment;
            _repPayment = repPayment;
            _translateManager = translate;
            _paymentsUtils = new PaymentsUtils(_repPayment, _translateManager);
            _merchantHelper = new MerchantHelper(_repPayment);
        }
        public ActionResult Merchant(Payer payer, string language)
        {
            _paymentsUtils.SetLanguage(language);

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

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

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