using System;
using System.Web;
using Platnosci.Core.Linq;
using System.Threading;
using System.Globalization;
using System.Configuration;
using System.Security.Principal;
using Platnosci.Core.Interface;


namespace Platnosci.Models
{
    public class FunkcjePlatnosci
    {
        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 IRepository<PlatnosciEcard> _repPayment;
        private readonly ITranslateManager _translateManager;

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

        public FunkcjePlatnosci(IRepository<PlatnosciEcard> repPayment)
        {
            _repPayment = repPayment;
            _translateManager = new Translation();    
        }
        public FunkcjePlatnosci(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 (waluta > 0 && (miano != "" || miano.ToUpper() != "PLN"))
                brutto += "(" + (waluta.ToString()).Replace(",", ".") + " " + miano.ToUpper() + ")";

            return brutto;
        }

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

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

            if (waluta.Currency == PLN)
                waluta.Amount = Convert.ToInt32(platnosc.Brutto * 100);
            else
                waluta.Amount = 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"];

            if (css == "truck") 
                str = HttpContext.GetGlobalResourceObject("tlumaczenia", "adresTruck") + " - ";
            else if (css == "admoto") 
                str = HttpContext.GetGlobalResourceObject("tlumaczenia", "adresAdmoto") + " - ";

            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(vPlatnosciEcard 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 = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToUpper();
            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(vPlatnosciEcard 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);
        }
    }
}