using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Baza_Reklam.Classes.Helpers;
using Baza_Reklam.Classes.Model;
using Baza_Reklam.Classes.Repositories;

namespace Baza_Reklam
{
    public partial class SubscriptionForm : Form
    {
        //TODO: Create BaseClass for all forms and inherit from it - there can be defined stuff like connection strings and other dependecies...
        private readonly string _connectionString = ConnString.getConnString().Value;

        private readonly IRepository<Customer> _customerRepository;
        private readonly IRepository<SubscriptionType> _subscriptionTypeRepository;
        private readonly List<SubscriptionType> _subscriptionTypes = new List<SubscriptionType>();
        private readonly Customer _customer;
        private Subscription _subscript;

        private SubscriptionType CurrentSubscriptionType
        {
            get
            {
                if (cbSubscriptionType.SelectedItem == null || ((SubscriptionType)cbSubscriptionType.SelectedItem).Id <= 0) return null;
                return (SubscriptionType)cbSubscriptionType.SelectedItem;
            }
        }

        public SubscriptionForm(int customerId, Subscription subscript)
        {
            InitializeComponent();

            _customerRepository = new CustomerRepository(_connectionString);
            _customer = _customerRepository.Find(customerId);

            _subscriptionTypeRepository = new SubscriptionTypeRepository(_connectionString);
            _subscriptionTypes = _subscriptionTypeRepository.FindAll();

            _subscript = subscript;

            BindControls();
        }
/*
        [Obsolete("Use ComboBoxHelper after merge from ReklamaReorganizacja branch")]
        static void BindComboBox<T>(IEnumerable<T> list, ComboBox comboBox)
        {
            comboBox.Items.Clear();
            foreach (T item in list)
            {
                comboBox.Items.Add(item);
            }
        }
*/
        private void BindControls()
        {
            lblCustomerName.Text = _customer.Name;

            //BindComboBox(_subscriptionTypes, cbSubscriptionType);
            ComboBoxHelper.Bind(_subscriptionTypes, cbSubscriptionType);

            cbSubscriptionType.DisplayMember = "Name";
            cbSubscriptionType.ValueMember = "Id";

            cbSubscriptionType.Items.Insert(0, new SubscriptionType(0, 0, "-- proszę wybrać --", 0, 0, 0));
            cbSubscriptionType.SelectedIndex = 0;

            cbCurrency.SelectedIndex = 0;
        }

        private void SetControls(bool enable)
        {
            numSubscriptionCount.Value = 1;
            numDiscount.Value = 0;
            if (enable)
            {
                // numSubscriptionCount.Enabled = true;
                numDiscount.Enabled = true;
                txtPricePln.Text = CurrentSubscriptionType.PricePln.ToString();
                txtPriceEur.Text = CurrentSubscriptionType.PriceEur.ToString();
                numSubscriptionCount.Value = (decimal)CurrentSubscriptionType.AmtMounth;
                ReCalculatePrices();
            }
            else
            {
                // numSubscriptionCount.Enabled = false;
                numDiscount.Enabled = false;
                txtPricePln.Text = string.Empty;
                txtPriceEur.Text = string.Empty;
                txtTotalPricePln.Text = string.Empty;
                txtTotalPriceEur.Text = string.Empty;
            }
        }

        private void ReCalculatePrices()
        {
            txtTotalPricePln.Text = (numSubscriptionCount.Value * CurrentSubscriptionType.PricePln * (1 - (numDiscount.Value / 100))).ToString("N2");
            txtTotalPriceEur.Text = (numSubscriptionCount.Value * CurrentSubscriptionType.PriceEur * (1 - (numDiscount.Value / 100))).ToString("N2");
        }

        private void cbSubscriptionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbSubscriptionType.SelectedItem == null) return;

            SubscriptionType subscriptionType = (SubscriptionType)cbSubscriptionType.SelectedItem;

            numSubscriptionCount.Value = 1;

            SetControls(subscriptionType.Id > 0);
        }

        private void numSubscriptionCount_ValueChanged(object sender, EventArgs e)
        {
            if (CurrentSubscriptionType == null)
            {
                SetControls(false);
                return;
            }

            ReCalculatePrices();
        }

        private void numDiscount_ValueChanged(object sender, EventArgs e)
        {
            if (CurrentSubscriptionType == null)
            {
                SetControls(false);
                return;
            }

            ReCalculatePrices();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Subscription subscription = null;

            if (_subscript == null)
            {
                subscription = new Subscription();

                subscription.Guid = Guid.NewGuid();
                subscription.CreatedBy = User.Instance().Id;
                subscription.CreatedOn = DateTime.Now;
            }
            else
            {
                subscription = _subscript;
            }

            subscription.SubscriptionTypeId = CurrentSubscriptionType.Id;
            subscription.SubscriptionItems = (int)numSubscriptionCount.Value;
            subscription.Currency = cbCurrency.SelectedItem.ToString();
            subscription.BasePrice = subscription.Currency == "PLN"
                                              ? Decimal.Parse(txtPricePln.Text)
                                              : Decimal.Parse(txtPriceEur.Text);
            subscription.Discount = numDiscount.Value / 100;

            subscription.Vat = subscription.Currency == "PLN"
                                              ? (decimal)VatHelper.PL22
                                              : (decimal)VatHelper.EU00;

            subscription.TotalPrice = subscription.Currency == "PLN"
                                              ? Decimal.Parse(txtTotalPricePln.Text)
                                              : Decimal.Parse(txtTotalPriceEur.Text);

            subscription.UpdatedBy = User.Instance().Id;
            subscription.UpdatedOn = DateTime.Now;

            subscription.StartDate = new DateTime(dateStartDate.Value.Year,
                                                    dateStartDate.Value.Month,
                                                    dateStartDate.Value.Day);

            if (subscription.SubscriptionDetails != null)
                subscription.SubscriptionDetails.Clear();

            for (int i = 0; i < subscription.SubscriptionItems; i++)
            {
                SubscriptionDetail subscriptionDetail = new SubscriptionDetail();
                subscriptionDetail.Month = dateStartDate.Value.AddMonths(i).Month;
                subscriptionDetail.Year = dateStartDate.Value.AddMonths(i).Year;
                subscriptionDetail.Price = subscription.BasePrice * (1 - subscription.Discount);
                subscriptionDetail.PricePln = Decimal.Parse(txtPricePln.Text) * (1 - subscription.Discount);
                subscription.AddSubscriptionDetail(subscriptionDetail);
            }

            _customer.AddSubscription(subscription);
            _customerRepository.Save(_customer);

            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void cbSubscriptionType_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ValidationHelper.IsComboValueSelected(cbSubscriptionType, 0, "Proszę wybrać typ abonamentu", e, errorProvider);
        }

        private void SubscriptionForm_Load(object sender, EventArgs e)
        {
            if (_subscript == null)
                return;

            cbSubscriptionType.SelectedIndex = 0;
            
            foreach (SubscriptionType st in cbSubscriptionType.Items)
                if (st.Id == _subscript.SubscriptionTypeId)
                {
                    cbSubscriptionType.SelectedItem = st;
                    break;
                }

            numSubscriptionCount.Value = 1;
            dateStartDate.Value = _subscript.StartDate;
            cbCurrency.Text = _subscript.Currency;
            txtPricePln.Text = _subscript.BasePrice.ToString();
            //txtPriceEur;
            txtTotalPricePln.Text = _subscript.TotalPrice.ToString();
            //txtTotalPriceEur;
            numDiscount.Value = _subscript.Discount * 100;
            numSubscriptionCount.Value = _subscript.SubscriptionItems;
        }
    }
}