using System;
using System.Web;
using System.Threading;
using System.Globalization;
using System.Configuration;
using System.Security.Principal;
using adMoto.Payments.Core;
using adMoto.Payments.Core.Data;
using adMoto.Payments.Core.Interfaces;


namespace adMoto.Payments.Web.Models
{
    public class PaymentsUtils
    {
        public const string EUR = "978";
        public const string GBP = "826";
        public const string USD = "789";
        public const string PLN = "985";
        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 readonly IRepository<PlatnosciEcard> _repPayment;
        private readonly ITranslateManager _translateManager;

        public PaymentsUtils()
        {
            _repPayment = new Repository<PlatnosciEcard>(new DataContext());
            _translateManager = new Translation();     
        }

        public PaymentsUtils(IRepository<PlatnosciEcard> repPayment)
        {
            _repPayment = repPayment;
            _translateManager = new Translation();    
        }
        public PaymentsUtils(IRepository<PlatnosciEcard> repPayment, ITranslateManager translate)
        {
            _repPayment = repPayment;
            _translateManager = translate;
        }
        public string BruttoToString(decimal? kwota, decimal? waluta, string miano)
        {
            var brutto = String.Format("{0:0.00}", kwota.ToString().Replace(",", ".")) + " PLN ";

            if (!String.IsNullOrEmpty(miano))
                if (waluta > 0 && miano.ToUpper() != "PLN")
                    brutto += "(" + (waluta.ToString()).Replace(",", ".") + " " + miano.ToUpper() + ")";
            
            return brutto;
        }

        public bool UserIdentity(Invoice platnosc, string userName)
        {
            return platnosc != null && platnosc.nip == userName;
        }

        public Waluta SetAmount(Invoice platnosc)
        {
            var waluta = new Waluta {Currency = GetCurrency(platnosc.waluta_miano)};

            waluta.Amount = waluta.Currency == PLN ? Convert.ToInt32(platnosc.Brutto * 100) : Convert.ToInt32(platnosc.waluta_brutto * 100);
            
            return waluta;
        }

        public string GetCurrency(string currency)
        {
            if (string.IsNullOrEmpty(currency)) 
                return PLN; 

            switch (currency.ToUpper())
            {
                case "EUR":
                    return EUR;
                case "GBP":
                    return GBP;
                case "USD":
                    return USD;
                default:
                    return PLN;
            }
        }

        public string SetLanguage(string lang)
        {
            switch (lang)
            {
                case "de":
                case "en":
                case "pl":
                    if (lang != Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower())
                    {
                        var culture = "pl-PL";
                        switch (lang)
                        {
                            case "pl":
                                culture = "pl-PL";
                                break;
                            case "en":
                                culture = "en-US";
                                break;
                            case "de":
                                culture = "de-DE";
                                break;
                        }

                        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
                        Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
                    }
                    break;
            }
            return CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToLower();
        }

        public string SetTitle()
        {
            var str = "";
            var css = ConfigurationManager.AppSettings["Css"];

            switch (css)
            {
                case "truck":
                    str = HttpContext.GetGlobalResourceObject("tlumaczenia", "adresTruck") + " - ";
                    break;
                case "admoto":
                    str = HttpContext.GetGlobalResourceObject("tlumaczenia", "adresAdmoto") + " - ";
                    break;
            }

            return str;
        }

        public void SetUserLogger(string nip, string faktura)
        {

            var user = nip + "-" + faktura;
            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user, ""), null);
        }

        public ErrorViewData InitErrorViewData(string errortxt, int idFaktury)
        {
            var er = new ErrorViewData { Error = errortxt, InvoiceId = idFaktury };
            return er;
        }
        public PlatnosciEcard CreateAndAddNewPyment(Invoice platnosc, Waluta waluta, Payer payer, string sessionId)
        {
            var newPayment = new PlatnosciEcard();
            newPayment.IDFaktury = platnosc.ID_faktury;
            newPayment.ORDERDESCRIPTION = platnosc.Faktura_Numer;
            newPayment.nip = platnosc.nip;
            newPayment.nrZlecenia = "";
            newPayment.AMOUNT = waluta.Amount;
            newPayment.CURRENCY = waluta.Currency;
            newPayment.SESSIONID = sessionId;
            newPayment.NAME = payer.FirstName;
            newPayment.SURNAME = payer.LastName;
            newPayment.AUTODEPOSIT = true;
            newPayment.LANGUAGE = GetLanguage(); //ustawiamy jezyk, w ktorym ma byc wyświetlany formularz na stronie eCard
            newPayment.CHARSET = KODOWANIE;
            newPayment.COUNTRY = KOD_POLSKA;
            newPayment.JS = true;
            newPayment.PAYMENTTYPE = CARDS;
            newPayment.Data = DateTime.Now;
            newPayment.Status = null;
            newPayment.Status_data = null;

            _repPayment.Insert(newPayment);
            return newPayment;
        }

        public ErrorViewData IsError(Invoice platnosc, String userName)
        {
            var errortxt = "";

            if (platnosc == null)
                errortxt = _translateManager.Translate("tlumaczenia", "brakdanych");
            else if (!UserIdentity(platnosc, userName))
                errortxt = _translateManager.Translate("tlumaczenia", "weryfikacja");

            return InitErrorViewData(errortxt, 0);
        }

        public string GetLanguage()
        {
            var language = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpper();
            
            if (language != "PL" && language != "EN" && language != "DE")
                return "PL";  //domyślny jezyk, w ktorym ma byc wyświetlony formularz na stronie eCard
            
            return language;
        }
    }
}