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_brutto, string miano)
        {
            var brutto = String.Format("{0:0.00}", kwota.ToString().Replace(",", ".")) + " PLN ";

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

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

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

            waluta.Amount = waluta.Currency == PLN ? Convert.ToInt32(invoice.Brutto * 100) : Convert.ToInt32(invoice.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 void SetLanguage(string lang)
        {
            if (lang == Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower()) return;

            string culture;
            switch (lang)
            {
                case "en":
                    culture = "en-GB";
                    break;
                case "de":
                    culture = "de-DE";
                    break;
                default:
                    culture = "pl-PL";
                    break;
            }

            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag(culture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(culture);
        }

        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 invoice, Waluta waluta, Payer payer, string sessionId)
        {
            var payment = new PlatnosciEcard();
            payment.IDFaktury = invoice.ID_faktury;
            payment.ORDERDESCRIPTION = invoice.Faktura_Numer;
            payment.nip = invoice.nip;
            payment.nrZlecenia = "";
            payment.AMOUNT = waluta.Amount;
            payment.CURRENCY = waluta.Currency;
            payment.SESSIONID = sessionId;
            payment.NAME = payer.FirstName;
            payment.SURNAME = payer.LastName;
            payment.AUTODEPOSIT = true;
            payment.LANGUAGE = GetLanguage(); //ustawiamy jezyk, w ktorym ma byc wyświetlany formularz na stronie eCard
            payment.CHARSET = KODOWANIE;
            payment.COUNTRY = KOD_POLSKA;
            payment.JS = true;
            payment.PAYMENTTYPE = CARDS;
            payment.Data = DateTime.Now;
            payment.Status = null;
            payment.Status_data = null;

            _repPayment.Insert(payment);
            return payment;
        }

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

            if (invoice == null)
                errortxt = _translateManager.Translate("tlumaczenia", "brakdanych");
            else if (!UserIdentity(invoice, 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;
        }
    }
}