using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BazaZamowien.Classes;

namespace BazaZamowien
{
    public partial class premieForm : Form
    {
        private bool queryExist;
        private SqlCommand refreshCommand = new SqlCommand();

        private static premieForm premieFormInstace;

        SqlCommand command = new SqlCommand();

        public static premieForm getPremieForm(MDImainForm parent)
        {
            if (premieFormInstace == null)
            {
                premieFormInstace = new premieForm(parent);
            }
            return premieFormInstace;
        }

        private premieForm(MDImainForm parent)
        {
            InitializeComponent();

            this.MdiParent = parent;

            this.pREMIE2TableAdapter.Connection.ConnectionString = ConnString.getConnString().PremieConnStr;

            PremieDBBindings.bindujDzialy((ComboBox)dzialyToolStripComboBox.Control, User.getUser().PremieGrupa);
            PremieDBBindings.bindujPracownikow((ComboBox)pracownikToolStripComboBox.Control, User.getUser().PremieGrupa);

            adminToolStripButton.Visible = toolStripSeparator2.Visible = User.getUser().PremieGrupa == 22;            
            wspolczynnikiToolStripButton.Visible = toolStripSeparator1.Visible = (User.getUser().PremieGrupa == 22 || User.getUser().PremieGrupa == 1);
        }

        private void premieForm_Load(object sender, EventArgs e)
        {
            danePoczatkowe();

            uprawnienia();
        }

        private void dodajToolStripButton_Click(object sender, EventArgs e)
        {
            premiaForm pf = new premiaForm(0);
            if (pf.ShowDialog() == DialogResult.OK)
            {
                danePoczatkowe();
            }
        }

        private void edytujToolStripButton_Click(object sender, EventArgs e)
        {
            if (pREMIE2BindingSource.Current != null)
            {
                DataRowView row = (DataRowView)pREMIE2BindingSource.Current;
                int ID = Convert.ToInt32(row["ID"]);

                premiaForm pf = new premiaForm(ID);
                if (pf.ShowDialog() == DialogResult.OK)
                {
                    odswiez();
                }
            }

        }

        private void usunToolStripButton_Click(object sender, EventArgs e)
        {
            if (pREMIE2BindingSource.Current != null)
            {
                DataRowView row = (DataRowView)pREMIE2BindingSource.Current;
                int ID = Convert.ToInt32(row["ID"]);

                if (MessageBox.Show("Czy na pewno chcesz usun¹æ rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    pREMIE2TableAdapter.Delete(ID);
                    odswiez();
                }
            }

        }

        private void uprawnienia()
        {
            usunToolStripButton.Visible = User.getUser().St_kierownik;
            dzialyToolStripComboBox.Enabled = !(User.getUser().IDEDzialuCT == 8);
        }

        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            command.Connection = new SqlConnection(ConnString.getConnString().PremieConnStr);
            command.CommandText = "select * from premie2 where 1=1 ";
            command.Parameters.Clear();

            if (rokToolStripTextBox.Text != "")
            {
                int i;
                if (!Int32.TryParse(rokToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj poprawny rok.");
                    return;
                }

                command.CommandText += " and (Rok=@rok) ";
                command.Parameters.AddWithValue("@rok", i);
            }

            if (msToolStripTextBox.Text != "")
            {
                int i;
                if (!Int32.TryParse(msToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj poprawny rok.");
                    return;
                }

                command.CommandText += " and (miesiac=@ms) ";
                command.Parameters.AddWithValue("@ms", i);
            }

            //reklama ma jeszcze filt po oddzialach, reszta nie musi
            if (User.getUser().IDEDzialuCT == 8)
            {
                if (pracownikToolStripComboBox.SelectedItem != null)
                {
                    command.CommandText += "  and IDEPracownika=@ide ";
                    command.Parameters.AddWithValue("@ide", ((BoundItem)pracownikToolStripComboBox.SelectedItem).IDEvalue1);
                }
                else
                {
                    command.CommandText += "  and IDEPracownika in (select IDePracownik from dbo.PODWLADNOSC where ideKierownik =@kier) ";
                    command.Parameters.AddWithValue("@kier", User.getUser().IDE_CT);
                }
            }
            else
            {
                if (dzialyToolStripComboBox.SelectedItem != null)
                {
                    command.CommandText += "  and Dzial=@dzial ";
                    command.Parameters.AddWithValue("@dzial", dzialyToolStripComboBox.SelectedItem.ToString());
                }
                else
                {
                    command.CommandText += "  and Dzial in (select dzial from dbo.GrupaDzial left join dbo.Dzialy  on" +
                        " dzialy.IDE = grupaDzial.IDEdzial where dbo.GrupaDzial.IDEGrupy = @grupa)";
                    command.Parameters.AddWithValue("@grupa", User.getUser().PremieGrupa);

                }

                if (pracownikToolStripComboBox.SelectedItem != null)
                {
                    command.CommandText += "  and IDEPracownika=@ide ";
                    command.Parameters.AddWithValue("@ide", ((BoundItem)pracownikToolStripComboBox.SelectedItem).IDEvalue1);
                }
                else
                {
                    command.CommandText += "  and IDEPracownika in (select distinct IdePracownik from dbo.PODWLADNOSC " +
                      " where ideDzial in (select IDEDzial from dbo.GrupaDzial where IDEGrupy = @grupa2))";
                    command.Parameters.AddWithValue("@grupa2", User.getUser().PremieGrupa);
                }
            }
            
            pREMIEDataSet.PREMIE2.Clear();

            SqlDataAdapter adapter = new SqlDataAdapter(command);
            adapter.Fill(pREMIEDataSet.PREMIE2);

            this.refreshCommand = command;
            this.queryExist = true;

            this.Cursor = Cursors.Default;
        }

        private void filtrToolStripButton_Click(object sender, EventArgs e)
        {
            rokToolStripTextBox.Text = "";

            msToolStripTextBox.Text = "";

            dzialyToolStripComboBox.SelectedIndex = -1;

            pracownikToolStripComboBox.SelectedIndex = -1;
        }

        /// <summary>
        /// ostatnio dodane
        /// </summary>
        private void danePoczatkowe()
        {

            string query = "select top 20 * from premie2";


            if (User.getUser().IDEDzialuCT == 8)
            {
                query += " where idePracownika in (select IDePracownik from dbo.PODWLADNOSC where ideKierownik =" + User.getUser().IDE_CT + ")";
            }
            else
            {
                query += " where Dzial in (select dzial from dbo.GrupaDzial left join dbo.Dzialy on";
                query += " dzialy.IDE = grupaDzial.IDEdzial where dbo.GrupaDzial.IDEGrupy = @grupa) ";
            }

            query += " and rok >= year(getdate()) - 1 ";
            query += " ORDER BY ID desc";
           
            SqlCommand command = new SqlCommand();
            command.CommandText = query;
            command.Connection = new SqlConnection(ConnString.getConnString().PremieConnStr);
            command.Parameters.AddWithValue("@grupa", User.getUser().PremieGrupa);


            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = command;
            

            this.pREMIEDataSet.PREMIE2.Clear();

            adapter.Fill(this.pREMIEDataSet.PREMIE2);

            this.refreshCommand = command;
            this.queryExist = true;

        }

        private void odswiez()
        {
            if (queryExist)
            {
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = this.refreshCommand;

                this.pREMIEDataSet.PREMIE2.Clear();

                adapter.Fill(this.pREMIEDataSet.PREMIE2);
            }
        }

        private void wspolczynnikiToolStripButton_Click(object sender, EventArgs e)
        {
            PremieWspolczynniki premieWspolczynniki = new PremieWspolczynniki();
            premieWspolczynniki.ShowDialog();
        }

        private void adminToolStripButton_Click(object sender, EventArgs e)
        {
            AdminFormPremie adminPremieForm = new AdminFormPremie();
            adminPremieForm.ShowDialog();
        }

        private void emailToolStripButton_Click(object sender, EventArgs e)
        {
            if (pREMIE2BindingSource.Current != null)
            {
                DataRowView row = (DataRowView) pREMIE2BindingSource.Current;
                int IDEpremia = Convert.ToInt32(row["ID"]);
                
                MailForm mailForm = new MailForm();
                PremieMail.initMailForm(mailForm,IDEpremia);
                mailForm.ShowDialog();
            }
        }

        private void exportToolStripButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            ExcelHandler ex = new ExcelHandler();
            ex.exportToExcel(pREMIE2DataGridView);

            this.Cursor = Cursors.Default;
        }

        private void drukujToolStripButton_Click(object sender, EventArgs e)
        {
            PrintDGV.Print_DataGridView(pREMIE2DataGridView,100);
        }
    }
}