using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Baza_Reklam.Classes.Interfaces;

namespace Baza_Reklam
{
    public partial class ProvisionForm : Form, IForm
    {

        private short rok;
        private short miesiac;
        private int agencja;


        /// <summary>
        /// Klasa pomocnicza do wyświetlania w 0 - 2 w gridzie
        /// </summary>
        class Ocena
        {
            private int label;
            private Single value;

            public int Label
            {
                get { return label; }
                set { label = value; }
            }

            public Single Value
            {
                get { return value; }
                set { this.value = value; }
            }

            public Ocena(int l, Single v)
            {
                label = l;
                value = v;
            }
        }




        private static ProvisionForm provisionForm;

        public static ProvisionForm getProvisionForm(MDIBazaReklam parent)
        {
            if (provisionForm == null)
            {
                provisionForm = new ProvisionForm(parent);
            }
            return provisionForm;
        }

        public ProvisionForm(Form parent)
        {
            InitializeComponent();

            MdiParent = parent;

            pLANTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            agencjeTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;

            //bindowanie ocen z comboBoxColumn
            List<Ocena> oceny = new List<Ocena>();
            oceny.Add(new Ocena(0, 0));
            oceny.Add(new Ocena(1, 50));
            oceny.Add(new Ocena(2, 100));

            OCENAComboCoxColumn.DataSource = oceny;
            OCENAComboCoxColumn.DisplayMember = "label";
            OCENAComboCoxColumn.ValueMember = "value";

            dodajPlanToolStripButton.Enabled = User.Instance().St_kierownik;
            usunToolStripButton.Enabled = User.Instance().St_kierownik;
        }

        private void ProvisionForm_Load(object sender, EventArgs e)
        {
            rokToolStripTextBox.Text = DateTime.Today.Year.ToString();
            msToolStripTextBox.Text = DateTime.Today.Month.ToString();

            ((ComboBox)agencjaToolStripComboBox.Control).DataSource = agencjeTableAdapter1.GetData();
            ((ComboBox)agencjaToolStripComboBox.Control).DisplayMember = "Symbol";
            ((ComboBox)agencjaToolStripComboBox.Control).ValueMember = "ID_Agencji";

            ((ComboBox)agencjaToolStripComboBox.Control).SelectedValue = User.Instance().IdAgencji;

            if (!User.Instance().St_kierownik)
            {
                agencjaToolStripComboBox.Enabled = false;
            }

        }

        /*
                private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
                {
                    SqlCommand command = new SqlCommand();
                    command.Connection = new SqlConnection(ConnString.getConnString().Value);

                    if (e.Node != null)
                    {
                        switch (e.Node.Level)
                        {
                            case 0:
                                e.Node.Nodes.Clear();

                                TreeNode node;

                                command.CommandText = "select distinct datepart(year,DATA_W) as rok from dbo.NR where datepart(year,DATA_W) is not null and datepart(year,DATA_W)>= 2003 order by rok desc";
                                command.Connection.Open();
                                SqlDataReader reader = command.ExecuteReader();

                                while (reader.Read())
                                {
                                    node = new TreeNode(reader.GetValue(0).ToString());
                                    node.Name = reader.GetValue(0).ToString();

                                    for (int i = 12; i >= 1; i--)
                                    {
                                        TreeNode node2 = new TreeNode(i.ToString());
                                        node2.Name = i.ToString();
                                        //  node2.Nodes.Add(new TreeNode());
                                        node.Nodes.Add(node2);
                                    }
                                    e.Node.Nodes.Add(node);
                                }
                                command.Connection.Close();

                                break;
                            case 1:
                                break;
                            case 2:
                                break;
                        }
                    }
                }
        */

        /// <summary>
        ///  Pobiera dane o kontaktach i budżecie.
        /// </summary>
        private void pobierzDaneToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            SqlCommand command = new SqlCommand();
            command.Connection = new SqlConnection(ConnString.getConnString().Value);
            command.CommandType = CommandType.StoredProcedure;

            command.CommandText = "PROC_WYLICZ_I_ZAPISZ_DANE_O_KONTAKTACH_I_BUDZECIE";
            command.Parameters.AddWithValue("@rok", rok);
            command.Parameters.AddWithValue("@ms", miesiac);

            command.Connection.Open();

            SqlTransaction transaction = command.Connection.BeginTransaction();

            command.Transaction = transaction;

            try
            {
                command.ExecuteNonQuery();
                transaction.Commit();
                MessageBox.Show("Dane pobrano!");
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                command.Connection.Close();
                rEKLAMADataSet.PLAN.Clear();
                pLANTableAdapter.FillByAgencja(rEKLAMADataSet.PLAN, rok, miesiac, agencja);
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// Wylicza i zapisuje prowizję agenta do planu
        /// </summary>
        private void zapiszToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            SqlCommand command = new SqlCommand();

            command.Connection = new SqlConnection(ConnString.getConnString().Value);

            command.CommandType = CommandType.StoredProcedure;

            command.CommandText = "PROC_WYLICZ_I_ZAPISZ_PROWIZJE_AGENTA_DO_PLANU";
            command.Parameters.AddWithValue("@rok", rok);
            command.Parameters.AddWithValue("@ms", miesiac);
            command.Parameters.AddWithValue("@id_Agencji", agencja);
            command.Connection.Open();

            SqlTransaction transaction = command.Connection.BeginTransaction();

            command.Transaction = transaction;

            try
            {
                command.ExecuteNonQuery();
                transaction.Commit();
                MessageBox.Show("Prowizja została zapisana!");
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                command.Connection.Close();

                rEKLAMADataSet.PLAN.Clear();

                pLANTableAdapter.FillByAgencja(rEKLAMADataSet.PLAN, rok, miesiac, agencja);

                Cursor = Cursors.Default;
            }
        }

        private void naniesNaReklamyToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            SqlCommand command = new SqlCommand();

            command.Connection = new SqlConnection(ConnString.getConnString().Value);

            command.CommandType = CommandType.StoredProcedure;

            // command.CommandText = "PROC_WYLICZ_I_ZAPISZ_PROWIZJE_DO_REKLAM";
            command.CommandText = "PROC_WYLICZ_I_ZAPISZ_PROWIZJE";
            command.Parameters.AddWithValue("@rok", rok);
            command.Parameters.AddWithValue("@ms", miesiac);
            command.Parameters.AddWithValue("@idAgencji", agencja);

            command.Connection.Open();

            SqlTransaction transaction = command.Connection.BeginTransaction();

            command.Transaction = transaction;

            try
            {
                command.ExecuteNonQuery();
                transaction.Commit();
                MessageBox.Show("Prowizja została naniesiona na zlecenia");
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                command.Connection.Close();
                Cursor = Cursors.Default;
                MessageBox.Show("Prowizja naniesiona na zlecenia");
            }
        }

        private void dodajPlanToolStripButton_Click(object sender, EventArgs e)
        {
            OcenaAddForm oaf = new OcenaAddForm();
            oaf.Show();
        }

        private void usunToolStripButton_Click(object sender, EventArgs e)
        {
            if (pLANBindingSource.Current != null)
            {
                if (MessageBox.Show("Czy na pewno usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    pLANBindingSource.RemoveCurrent();
                    pLANBindingSource.EndEdit();
                    pLANTableAdapter.Update(rEKLAMADataSet.PLAN);
                }
            }
        }

        private void zapiszDaneToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            if (Validate())
            {
                pLANBindingSource.EndEdit();
                pLANTableAdapter.Update(rEKLAMADataSet.PLAN);
            }
            Cursor = Cursors.Default;

            MessageBox.Show("Zmiany zapisane");
        }

        /*
                private void ukryjKolumnyToolStripButton_Click(object sender, EventArgs e)
                {
                    rOKDataGridViewTextBoxColumn.Visible = rOKDataGridViewTextBoxColumn.Visible ? false : true;

                    mSDataGridViewTextBoxColumn.Visible = mSDataGridViewTextBoxColumn.Visible ? false : true;
                }
        */

        private void prowizjeDataGridView_Leave(object sender, EventArgs e)
        {
            //ukrytyLabel.Select();
            prowizjeDataGridView.EndEdit();
            //pLANBindingSource.EndEdit();

            REKLAMADataSet.PLANDataTable changes = rEKLAMADataSet.PLAN.GetChanges(DataRowState.Modified) as
                REKLAMADataSet.PLANDataTable;

            if (changes != null)
            {
                if (Validate())
                {
                    pLANBindingSource.EndEdit();
                    pLANTableAdapter.Update(rEKLAMADataSet.PLAN);
                }
            }
        }

        /// <summary>
        /// Podsumowuje budżet do wykonania
        /// </summary>
        private void uzupelnijBDsuma()
        {
            int kasa = 0;
            foreach (DataRowView r in pLANBindingSource.List)
            {
                kasa += Convert.ToInt32(r["BUDZET"]);
            }
            BDsumaTextBox.Text = String.Format("{0:C}", kasa);
        }

        /// <summary>
        /// Podsumowuje budżet wykonany
        /// </summary>
        private void uzupelnijBDWykonanySuma()
        {
            int kasa = 0;
            foreach (DataRowView r in pLANBindingSource.List)
            {
                kasa += Convert.ToInt32(r["W_BUDZET"]);
            }
            BDWykonanySumaTextBox.Text = String.Format("{0:C}", kasa);
        }

        /// <summary>
        /// Zamienia wpisaną liczbę do decimal
        /// </summary>
        private void prowizjeDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            ukrytyLabel.Select();
            prowizjeDataGridView.EndEdit();
            pLANBindingSource.EndEdit();

            if (prowizjeDataGridView.Columns[e.ColumnIndex].Name == "PR_PROWIZJI")
            {

                if (Convert.ToDecimal(prowizjeDataGridView[e.ColumnIndex, e.RowIndex].Value) >= 1)
                {
                    prowizjeDataGridView[e.ColumnIndex, e.RowIndex].Value = Convert.ToDecimal(prowizjeDataGridView[e.ColumnIndex, e.RowIndex].Value) / 100;
                }
            }

            REKLAMADataSet.PLANDataTable changes = rEKLAMADataSet.PLAN.GetChanges(DataRowState.Modified) as
                 REKLAMADataSet.PLANDataTable;

            if (changes != null)
            {
                pLANBindingSource.EndEdit();
                pLANTableAdapter.Update(rEKLAMADataSet.PLAN);
            }
        }

        private void pLANBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            uzupelnijBDsuma();
            uzupelnijBDWykonanySuma();
        }


        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            if (rokToolStripTextBox.Text != "")
            {
                short i;
                if (!Int16.TryParse(rokToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy rok.");
                    Cursor = Cursors.Default;
                    return;
                }
            }
            else
            {
                MessageBox.Show("Podaj prawidłowy rok.");
                Cursor = Cursors.Default;
                return;
            }

            if (msToolStripTextBox.Text != "")
            {
                short i;
                if (!Int16.TryParse(msToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy miesiąc.");
                    Cursor = Cursors.Default;
                    return;
                }
            }
            else
            {
                MessageBox.Show("Podaj prawidłowy miesiąc.");
                Cursor = Cursors.Default;
                return;
            }

            if (((ComboBox)agencjaToolStripComboBox.Control).SelectedValue == null)
            {
                MessageBox.Show("Wybierz agencję");
                return;
            }

            rok = Convert.ToInt16(rokToolStripTextBox.Text);
            miesiac = Convert.ToInt16(msToolStripTextBox.Text);
            agencja = Convert.ToInt32(((ComboBox)agencjaToolStripComboBox.Control).SelectedValue);

            uprawnienia();

            sLOWNIKDataSet.AGENCI.Clear();
            rEKLAMADataSet.PLAN.Clear();

            aGENCITableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCI, agencja);
            pLANTableAdapter.FillByAgencja(rEKLAMADataSet.PLAN, rok, miesiac, agencja);
        }

        /*
        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {            
            this.Cursor = Cursors.WaitCursor;

            string query = "SELECT   top 1000 [PLAN].* FROM AGENCJE INNER JOIN AGENCI ON AGENCJE.Id_agencji = AGENCI.ID_AGENCJI " +
                " INNER JOIN [PLAN] ON AGENCI.Symbol = [PLAN].SYMBOL WHERE  1 = 1 ";

            SqlCommand command = new SqlCommand();
            command.CommandText = query;

            if (rokToolStripTextBox.Text != "")
            {
                short i;
                if (!Int16.TryParse(rokToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy rok.");
                    this.Cursor = Cursors.Default;
                    return;
                }
                command.CommandText += " AND [PLAN].rok = @rok ";
                command.Parameters.AddWithValue("@rok", rokToolStripTextBox.Text);
                this.rok = Convert.ToInt16(rokToolStripTextBox.Text);
            }            

            if (msToolStripTextBox.Text != "")
            {
                short i;
                if (!Int16.TryParse(msToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy miesiąc.");
                    this.Cursor = Cursors.Default;
                    return;
                }
                command.CommandText += " AND [PLAN].ms = @ms ";
                command.Parameters.AddWithValue("ms", msToolStripTextBox.Text);
                this.miesiac = Convert.ToInt16(msToolStripTextBox.Text);
            }

            if (((ComboBox)agencjaToolStripComboBox.Control).SelectedValue == null)
            {
                MessageBox.Show("Wybierz agencję");
                return;
            }
            else
            {
                command.CommandText += " AND AGENCJE.Id_Agencji=@agencja";
                command.Parameters.AddWithValue("@agencja", ((ComboBox)agencjaToolStripComboBox.Control).SelectedValue);
                this.agencja = Convert.ToInt32(((ComboBox)agencjaToolStripComboBox.Control).SelectedValue);
            }

          //  uprawnienia();    
            poblokujWiersze();
                     
            
            this.sLOWNIKDataSet.AGENCI.Clear();
            this.aGENCITableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCI, this.agencja);

            this.rEKLAMADataSet.PLAN.Clear();
           // this.pLANTableAdapter.FillByAgencja(this.rEKLAMADataSet.PLAN, this.rok, this.miesiac, this.agencja);

            command.Connection = new SqlConnection(ConnString.getConnString().Value);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = command;

            adapter.Fill(rEKLAMADataSet.PLAN);

            this.Cursor = Cursors.Default;   
        }

        private void poblokujWiersze()
        {
            if (User.Instance().St_kierownik)
            {
                prowizjeDataGridView.ReadOnly = false;
                foreach (DataGridViewRow r in prowizjeDataGridView.Rows)
                {
                    if (!((Convert.ToInt32(r.Cells["rOKDataGridViewTextBoxColumn"].Value) > DateTime.Today.Year) |
                        ((Convert.ToInt32(r.Cells["rOKDataGridViewTextBoxColumn"].Value) == DateTime.Today.Year) & (Convert.ToInt32(r.Cells["mSDataGridViewTextBoxColumn"].Value) >= DateTime.Today.Month - 1)) |
                        ((Convert.ToInt32(r.Cells["rOKDataGridViewTextBoxColumn"].Value) == DateTime.Today.Year - 1) & (Convert.ToInt32(r.Cells["mSDataGridViewTextBoxColumn"].Value) == 12) & (DateTime.Today.Month == 1))))
                    {
                        r.ReadOnly = true;
                    }
                }
            }
        }
        */

        private void uprawnienia()
        {
            if (User.Instance().St_kierownik)
            {

                if (!((rok > DateTime.Today.Year) |
                    ((rok == DateTime.Today.Year) & (miesiac >= DateTime.Today.Month - 1)) |
                    ((rok == DateTime.Today.Year - 1) & (miesiac == 12) & (DateTime.Today.Month == 1))))
                {
                    OCENAComboCoxColumn.Visible = false;
                    oCENADataGridViewTextBoxColumn.Visible = true;

                    prowizjeDataGridView.ReadOnly = true;
                    usunToolStripButton.Enabled = false;
                    pobierzDaneToolStripButton.Enabled = false;
                    naniesNaReklamyToolStripButton.Enabled = false;
                    zapiszDaneToolStripButton.Enabled = false;
                    zapiszToolStripButton.Enabled = false;

                }
                else
                {
                    OCENAComboCoxColumn.Visible = true;
                    oCENADataGridViewTextBoxColumn.Visible = false;
                    prowizjeDataGridView.ReadOnly = false;

                    usunToolStripButton.Enabled = true;
                    pobierzDaneToolStripButton.Enabled = true;
                    naniesNaReklamyToolStripButton.Enabled = true;
                    zapiszDaneToolStripButton.Enabled = true;
                    zapiszToolStripButton.Enabled = true;

                    stareProwizjeToolStripButton.Enabled = true;
                }
            }
        }

        private void prowizjeDataGridView_DataError_1(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadź poprawne dane");
        }

        private void ProvisionForm_Leave(object sender, EventArgs e)
        {
            prowizjeDataGridView.EndEdit();
            //pLANBindingSource.EndEdit();

            REKLAMADataSet.PLANDataTable changes = rEKLAMADataSet.PLAN.GetChanges(DataRowState.Modified) as
                REKLAMADataSet.PLANDataTable;

            if (changes != null)
            {
                if (Validate())
                {
                    pLANBindingSource.EndEdit();
                    pLANTableAdapter.Update(rEKLAMADataSet.PLAN);
                }
            }
        }

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            PrintDGV.Print_DataGridView(prowizjeDataGridView, 50);
        }

        private void wyczyscToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void przeliczStripButton_Click(object sender, EventArgs e)
        {

        }

        private void stareProwizjeToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            SqlCommand command = new SqlCommand();

            command.Connection = new SqlConnection(ConnString.getConnString().Value);

            command.CommandType = CommandType.StoredProcedure;

            command.CommandText = "PROC_WYLICZ_I_ZAPISZ_PROWIZJE_DO_REKLAM";
            command.Parameters.AddWithValue("@rok", rok);
            command.Parameters.AddWithValue("@ms", miesiac);

            command.Connection.Open();

            SqlTransaction transaction = command.Connection.BeginTransaction();

            command.Transaction = transaction;

            try
            {
                command.ExecuteNonQuery();
                transaction.Commit();
                MessageBox.Show("Prowizja została naniesiona na zlecenia");
            }
            catch (Exception)
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                command.Connection.Close();
                Cursor = Cursors.Default;
            }
        }

        public void CloseForm()
        {
            provisionForm = null;
        }
    }
}