using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Baza_Reklam.Classes.Repositories;
using Baza_Reklam.Classes.Model;

namespace Baza_Reklam
{
    public partial class ProvisionEditForm : Form
    {
        private ProvisionRepository repository;
        private AgentRepository agentRepository;
        private bool bReadData;
        private bool bUpdateValue;
        private List<Provision> changedProvisions;
        private int _y;
        private int _m;

        public ProvisionEditForm(int y, int m) : this()
        {
            _y = y;
            _m = m;
        }

        public ProvisionEditForm()
        {
            bReadData = true;

            InitializeComponent();

            changedProvisions = new List<Provision>();
            repository = new ProvisionRepository(ConnString.getConnString().Value);
            agentRepository = new AgentRepository(ConnString.getConnString().Value);

            List<string> oddz = agentRepository.FindOdzialProvision();
            toolStripCb_Oddzial.Items.Add("");
            foreach (string s1 in oddz)
                toolStripCb_Oddzial.Items.Add(s1);

            toolStripCb_Oddzial.SelectedIndex = 0;

            _y = DateTime.Today.Year;
            _m = DateTime.Today.Month;
        }

        private void ProvisionEditForm_Load(object sender, EventArgs e)
        {
            toolStripTb_rok.Text = _y.ToString();
            toolStripTb_mc.Text = _m.ToString();

            bReadData = true;

            agentsBindingSource.DataSource = null;
            agentsBindingSource.DataSource = agentRepository.FindAllProvision();

            provisionsDataGridView.AutoGenerateColumns = false;

            RefreshProvisions();
        }

        private void ProvisionEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = QuestionChange() == DialogResult.Cancel;
        }

        private void toolStripBtn_Refresh_Click(object sender, EventArgs e)
        {
            if (QuestionChange() == DialogResult.Cancel)
                return;

            RefreshProvisions();
        }

        private DialogResult QuestionChange()
        {
            if (changedProvisions.Count > 0)
            {
                switch (MessageBox.Show("Dane z " + toolStripTb_rok.Text + "-" + toolStripTb_mc.Text + " zostały zmienione.\nCzy chcesz zapiać zmiany?",
                        "Baza Reklam", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                {
                    case DialogResult.Yes:
                        if (Save())
                            return DialogResult.Yes;

                        return DialogResult.Cancel;

                    case DialogResult.No:
                        break;

                    case DialogResult.Cancel:
                        return DialogResult.Cancel;
                }
            }

            return DialogResult.No;
        }

        private void RefreshProvisions()
        {
            try
            {
                bReadData = true;
                provisionsDataGridView.DataSource = null;

                changedProvisions.Clear();

                int y, m;
                int.TryParse(toolStripTb_rok.Text, out y);
                int.TryParse(toolStripTb_mc.Text, out m);

                provisionsDataGridView.DataSource = repository.FindAll(y, m, (string)toolStripCb_Oddzial.SelectedItem);

                CountProvision();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                bReadData = false;
            }
        }

        private void CountProvision()
        {
            foreach (DataGridViewRow r in provisionsDataGridView.Rows)
                r.Cells["Prowizja"].Value = (double)((Provision)r.DataBoundItem).Netto * ((Provision)r.DataBoundItem).ProcentProwizji;
        }

        private bool Save()
        {
            bool bRet = false;
            try
            {
                if ((bRet = repository.Save(changedProvisions)) == true)
                {
                    changedProvisions.Clear();
                    foreach (DataGridViewRow r in provisionsDataGridView.Rows)
                        r.DefaultCellStyle.ForeColor = provisionsDataGridView.DefaultCellStyle.ForeColor;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return bRet;
        }

        private void provisionsDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (bReadData ||
                bUpdateValue)
                return;

            try
            {
                bUpdateValue = true;

                DataGridViewColumn col1 = provisionsDataGridView.Columns["Agent"];
                DataGridViewColumn col2 = provisionsDataGridView.Columns["ProcentProwizji"];
                DataGridViewColumn col3 = provisionsDataGridView.Columns["Prowizja"];
                DataGridViewColumn col4 = provisionsDataGridView.Columns["Netto"];

                if (col1 == null ||
                    col2 == null ||
                    col3 == null ||
                    col4 == null)
                    return;

                if (e.ColumnIndex == col1.Index)
                {
                    if (!changedProvisions.Contains((Provision)provisionsDataGridView.Rows[e.RowIndex].DataBoundItem))
                        changedProvisions.Add((Provision)provisionsDataGridView.Rows[e.RowIndex].DataBoundItem);

                    provisionsDataGridView.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
                else if (e.ColumnIndex == col2.Index)
                {
                    string s1 = provisionsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue.ToString();

                    string charsOk = ",.% ";

                    foreach (char c1 in s1)
                    {
                        if (!char.IsDigit(c1) &&
                            charsOk.IndexOf(c1) < 0)
                        {
                            // MessageBox.Show("Baza reklam", "Podaj prawidłową wartość prowizji!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }

                    s1 = s1.Replace("%", "");
                    s1 = s1.Replace(".", ",");

                    double prPorowizji;
                    if (!double.TryParse(s1, out prPorowizji))
                        return;

                    prPorowizji /= 100;

                    if (provisionsDataGridView.Rows[e.RowIndex].Cells[col4.Index].Value == null)
                        return;

                    double kwNetto = (double)(decimal)provisionsDataGridView.Rows[e.RowIndex].Cells[col4.Index].Value;

                    provisionsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = prPorowizji;
                    provisionsDataGridView.Rows[e.RowIndex].Cells[col3.Index].Value = (decimal)Math.Round(kwNetto * prPorowizji, 2);

                    if (!changedProvisions.Contains((Provision)provisionsDataGridView.Rows[e.RowIndex].DataBoundItem))
                        changedProvisions.Add((Provision)provisionsDataGridView.Rows[e.RowIndex].DataBoundItem);

                    provisionsDataGridView.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                }
            }
            finally
            {
                bUpdateValue = false;
            }
        }

        private void provisionsDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Podaj prawidłowe dane!", "Baza reklam", MessageBoxButtons.OK, MessageBoxIcon.Error);
/*
            if (e.ColumnIndex == provisionsDataGridView.Columns["Agent"].Index)
            {
                ;
            }
            else if (e.ColumnIndex == provisionsDataGridView.Columns["ProcentProwizji"].Index)
            {
                ;
            }
*/
        }

        private void toolStripBtnSave_Click(object sender, EventArgs e)
        {
            Save();
        }
    }
}