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 SubscriptionType CurrentSubscriptionType
        {
            get
            {
                if (cbSubscriptionType.SelectedItem == null || ((SubscriptionType)cbSubscriptionType.SelectedItem).Id <= 0) return null;
                return (SubscriptionType)cbSubscriptionType.SelectedItem;
            }
        }

        public SubscriptionForm(int customerId)
        {
            InitializeComponent();

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

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

            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);
            cbSubscriptionType.DisplayMember = "Name";
            cbSubscriptionType.ValueMember = "Id";

            cbSubscriptionType.Items.Insert(0, new SubscriptionType(0, 0, "-- proszę wybrać --", 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();
                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();
            txtTotalPriceEur.Text = (numSubscriptionCount.Value * CurrentSubscriptionType.PriceEur * (1 - (numDiscount.Value / 100))).ToString();
        }

        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 = new Subscription();

            subscription.Guid = Guid.NewGuid();
            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.CreatedBy = User.Instance().Id;
            subscription.CreatedOn = DateTime.Now;
            subscription.UpdatedBy = User.Instance().Id;
            subscription.UpdatedOn = DateTime.Now;
            subscription.StartDate = dateStartDate.Value;

            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);
        }
    }
}