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 System.Globalization;

namespace Baza_Reklam
{
    public partial class InfoForm : Form
    {
        private static InfoForm infoform;

        public static InfoForm getInfoForm(MDIBazaReklam parent)
        {
            if (infoform == null) {
                infoform = new InfoForm(parent);
            }
            return infoform;
        }

        private int ostRok = DateTime.Today.Year;
        private int ostMs = DateTime.Today.Month;

        private InfoForm(MDIBazaReklam parent)
        {
            InitializeComponent();

            this.MdiParent = parent;

            //podmiana connstringa
            nAZWY_MODULOWTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            gRZBIETYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            koszty_BiuraTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            bUDZET_BIURTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            nRTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            daty_publikacjiTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            pLANY_PROWIZJITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kONTATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCJETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            lISTA_TYTULOWTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            pROMOCJETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kursy_WalutTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            ImageList imageList = new ImageList();
            imageList.Images.Add(Baza_Reklam.Properties.Resources.bullet_ball_glass_green);
            imageList.Images.Add(Baza_Reklam.Properties.Resources.bullet_ball_glass_red);
            datyPubTreeView.ImageList = imageList;
            datyPubTreeView.ImageIndex = 0;
            datyPubTreeView.SelectedImageIndex = 1;

            treeView3.ImageList = imageList;
            treeView3.ImageIndex = 0;
            treeView3.SelectedImageIndex = 1;

            treeView4.ImageList = imageList;
            treeView4.ImageIndex = 0;
            treeView4.SelectedImageIndex = 1;

            bindingNavigator3.Visible = true;
            bindingNavigator4.Visible = true;
            bindingNavigator6.Visible = true;
            bindingNavigator7.Visible = true;
            bindingNavigator8.Visible = true;
            bindingNavigator9.Visible = true;
            bindingNavigator10.Visible = true;
            bindingNavigator11.Visible = true;   
       
        }

        private void InfoForm_Load(object sender, EventArgs e)
        {            
           // this.aGENCJETableAdapter.FillByALL(this.sLOWNIKDataSet.AGENCJE);

            this.agencjeListBox.DataSource = this.aGENCJETableAdapter.GetDataByALL();
            this.agencjeListBox.DisplayMember = "Symbol";
            this.agencjeListBox.ValueMember = "Id_agencji";

            this.aGENCJETableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCJE, Convert.ToInt32(agencjeListBox.SelectedValue));
            this.aGENCITableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCI, Convert.ToInt32(agencjeListBox.SelectedValue));

            this.nowyAgentComboBox.DataSource = this.aGENCITableAdapter.GetDataByIdAgencjiAktywni(Convert.ToInt32(agencjeListBox.SelectedValue));
            this.nowyAgentComboBox.DisplayMember = "Symbol";
            this.nowyAgentComboBox.ValueMember = "Symbol";

            this.staryAgentComboBox.DataSource = this.aGENCITableAdapter.GetDataByNieaktywniIDAgencji(Convert.ToInt32(agencjeListBox.SelectedValue));
            this.staryAgentComboBox.DisplayMember = "Symbol";
            this.staryAgentComboBox.ValueMember = "Symbol";


            this.iDBIURADataGridViewTextBoxColumn.DataSource = this.aGENCJETableAdapter.GetData();
            this.iDBIURADataGridViewTextBoxColumn.DisplayMember = "Symbol";
            this.iDBIURADataGridViewTextBoxColumn.ValueMember = "Id_agencji";

            this.WindowState = FormWindowState.Maximized;

            this.nAZWY_MODULOWTableAdapter.FillByAll(this.sLOWNIKDataSet.NAZWY_MODULOW);

            generateNodes();
            generujTytuly();
            uprawnienia(); 
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                this.nRBindingSource.Filter = "[tyt]='" + e.Node.Text + "'";
            }       
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (infoTabControl.SelectedTab.Name)
            {
                case "naWydanTab":
                    this.sLOWNIKDataSet.NAZWY_MODULOW.Clear();
                    this.nRTableAdapter.Fill(this.sLOWNIKDataSet.NR);
                  //  this.nrWydanDataGridView.Sort(dATAWDataGridViewTextBoxColumn, ListSortDirection.Descending);
                    treeView1.SelectedNode = treeView1.Nodes["AMTNode"];
                    pozycjaAktualnegoWydania("AMT");
                    uzupelnijKalendarz();
                    break;
                case "modulyTab":
                    this.sLOWNIKDataSet.NR.Clear();
                    this.nAZWY_MODULOWTableAdapter.FillByAll(this.sLOWNIKDataSet.NAZWY_MODULOW);
                    break;
                case "oddzialyTab":
                    this.sLOWNIKDataSet.NAZWY_MODULOW.Clear();
                    this.sLOWNIKDataSet.NR.Clear();
                    this.pLANY_PROWIZJITableAdapter.Fill(this.sLOWNIKDataSet.PLANY_PROWIZJI);
                    if (aGENCJEBindingSource.Current != null) {
                        DataRowView row = (DataRowView)aGENCJEBindingSource.Current;
                        int idAgencji = Convert.ToInt32(row["Id_agencji"]);
                        this.kONTATableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.KONTA,idAgencji);
                        this.aGENCITableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCI,idAgencji);            
                    }
                    break;
                case "kursyWalutTabPage":
                    this.daty_publikacjiTableAdapter.Fill(this.sLOWNIKDataSet.Daty_publikacji);

                    TreeNode node;
                    foreach (DataRowView row in datypublikacjiBindingSource.List) { 
                        node = new TreeNode();
                        node.Text = (Convert.ToDateTime(row["Data_Publikacji"])).ToShortDateString();
                        node.Name = row["Numer_Tabeli"].ToString();
                        datyPubTreeView.Nodes.Add(node);                    
                    }
                    uprawnienia();
                    break;
                case "grzbietyTabPage":
                    this.lISTA_TYTULOWTableAdapter.FillAll(this.sLOWNIKDataSet.LISTA_TYTULOW);
                    this.pROMOCJETableAdapter.Fill(this.sLOWNIKDataSet.PROMOCJE);
                    this.gRZBIETYTableAdapter.Fill(this.sLOWNIKDataSet.GRZBIETY);
                    break;
                case "planyProwizyjneTabPage":
                    this.pLANY_PROWIZJITableAdapter.Fill(this.sLOWNIKDataSet.PLANY_PROWIZJI);
                    break;
                case "kosztyBiurTabPage":
                    treeView3.SelectedNode = treeView3.Nodes[User.getUser().IdAgencji.ToString()];
                    break;
                case "budzetTabPage":
                    treeView4.SelectedNode = treeView4.Nodes[User.getUser().IdAgencji.ToString()];
                    break;
                default:
                    break;
            }
        }

        private void treeView2_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                switch (e.Node.Level)
                {
                    case 0:
                        switch (e.Node.Name)
                        {
                            case "wszystkieNode":
                                this.nAZWYMODULOWBindingSource.Filter = "";
                                break;
                            case "TylkoAktywne":
                                this.nAZWYMODULOWBindingSource.Filter = "St_aktywny=1";
                                break;
                        }
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "wszystkieNode":
                                this.nAZWYMODULOWBindingSource.Filter = "[tytul]='" + e.Node.Text + "'";
                                break;
                            case "TylkoAktywne":
                                this.nAZWYMODULOWBindingSource.Filter = "St_aktywny=1 AND [tytul]='" + e.Node.Text + "'";
                                break;
                        }
                        break;
                    default:
                        this.nAZWYMODULOWBindingSource.Filter = "";
                        break;
                }
            }
        }
        private void InfoForm_Shown(object sender, EventArgs e)
        {
            uzupelnijKalendarz();   
        }

        private void nRBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            uzupelnijKalendarz();           
        }

        private void naWydanTab_Enter(object sender, EventArgs e)
        {
            uzupelnijKalendarz();  
        }

        private void nrWydanDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane");
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            nRBindingSource.EndEdit();
            nRTableAdapter.Update(sLOWNIKDataSet.NR);
            MessageBox.Show("Dane zapisane");
        }

        private void modulySaveToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            nAZWYMODULOWBindingSource.EndEdit();
            nAZWY_MODULOWTableAdapter.Update(sLOWNIKDataSet.NAZWY_MODULOW);
            MessageBox.Show("Dane zapisane");
        }

        private void modulyDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane");
        }
        

        private void zapiszAgencjeToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            aGENCJEBindingSource.EndEdit();
            aGENCJETableAdapter.Update(this.sLOWNIKDataSet.AGENCJE);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszAgentToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            aGENCIBindingSource.EndEdit();
            aGENCITableAdapter.Update(this.sLOWNIKDataSet.AGENCI);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszGrzbietyToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            gRZBIETYBindingSource.EndEdit();
            gRZBIETYTableAdapter.Update(this.sLOWNIKDataSet.GRZBIETY);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszTytultoolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            lISTA_TYTULOWBindingSource.EndEdit();
            lISTA_TYTULOWTableAdapter.Update(this.sLOWNIKDataSet.LISTA_TYTULOW);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszPromocjeToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            pROMOCJEBindingSource.EndEdit();
            pROMOCJETableAdapter.Update(this.sLOWNIKDataSet.PROMOCJE);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszPlanProwToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            pLANYPROWIZJIBindingSource.EndEdit();
            pLANY_PROWIZJITableAdapter.Update(this.sLOWNIKDataSet.PLANY_PROWIZJI);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszKosztyBiuraToolStripButton_Click_1(object sender, EventArgs e)
        {
            if (rokTextBox.Text == "")
            {
                MessageBox.Show("Podaj rok");
                return;
            }

            if (miesiacTextBox.Text == "")
            {
                MessageBox.Show("Podaj miesiac");
                return;
            }

            Validate();

            if (koszty_BiuraBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)koszty_BiuraBindingSource.Current;
                row["id_Agencji"] = treeView3.SelectedNode.Name;
            }
            koszty_BiuraBindingSource.EndEdit();
            koszty_BiuraTableAdapter.Update(this.sLOWNIKDataSet.Koszty_Biura);
            MessageBox.Show("Zmiany zapisane.");

            podsumujKosztyBiura();
        }
        
        private void zapiszBudzetToolStripButton_Click(object sender, EventArgs e)
        {
            budzetyDataGridView.EndEdit();
            Validate();
            bUDZETBIURBindingSource.EndEdit();
            bUDZET_BIURTableAdapter.Update(this.sLOWNIKDataSet.BUDZET_BIUR);
            MessageBox.Show("Zmiany zapisane.");
           
        }

        private void pROMOCJEDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane.");
        }

        private void gRZBIETYDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane.");
        }

        private void pLANY_PROWIZJIDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane.");
        }
                       
        private void treeView3_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                this.sLOWNIKDataSet.Koszty_Biura.Clear();
                this.koszty_BiuraTableAdapter.FillBy(this.sLOWNIKDataSet.Koszty_Biura, e.Node.Name);
                this.koszty_BiuraBindingSource.MoveLast();

                if (koszty_BiuraBindingSource.Current != null)
                {
                    DataRowView row = (DataRowView)koszty_BiuraBindingSource.Current;
                    this.ostRok = Convert.ToInt32(row["rok"]);
                    this.ostMs = Convert.ToInt32(row["miesiac"]);
                }
            }
        }

        private void treeView4_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                this.sLOWNIKDataSet.BUDZET_BIUR.Clear();
                this.bUDZET_BIURTableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.BUDZET_BIUR, Convert.ToInt32(e.Node.Name));
            }
        }

        private void budzetyDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane");
        }
               
        private void modulyDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
           // modulyDataGridView.EndEdit();
        }

        private void kursy_WalutDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
           // kursy_WalutDataGridView.EndEdit();
        }

        private void nrWydanDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //nrWydanDataGridView.EndEdit();
        }

        private void dataGridView1_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //dataGridView1.EndEdit();
        }

        private void kONTADataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //kONTADataGridView.EndEdit();
        }

        private void gRZBIETYDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
        }

        private void pROMOCJEDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //pROMOCJEDataGridView.EndEdit();
        }

        private void pLANY_PROWIZJIDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //pLANY_PROWIZJIDataGridView.EndEdit();
        }

        private void budzetyDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //budzetyDataGridView.EndEdit();
        }

        private void pLANY_PROWIZJIDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            ukrytyLabel.Select();
            if (pLANY_PROWIZJIDataGridView.Columns[e.ColumnIndex].Name != "dataGridViewTextBoxColumn15")
            {
                pLANY_PROWIZJIDataGridView.EndEdit();
                if (Convert.ToDecimal(pLANY_PROWIZJIDataGridView[e.ColumnIndex, e.RowIndex].Value) >= 1)
                {
                    pLANY_PROWIZJIDataGridView[e.ColumnIndex, e.RowIndex].Value = Convert.ToDecimal(pLANY_PROWIZJIDataGridView[e.ColumnIndex, e.RowIndex].Value) / 100;
                }
            }
        }

        private void datyPubTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.kursy_WalutTableAdapter.ClearBeforeFill = true;
            if (datyPubTreeView.SelectedNode != null)
            {
                this.kursy_WalutTableAdapter.FillByNrTabeli(this.sLOWNIKDataSet.Kursy_Walut, datyPubTreeView.SelectedNode.Name);
            }
            kursy_WalutDataGridView.Refresh();
        }

        private int pozycjaAktualnegoWydania(string tytul)
        {
            int position = 0;
            return position;
        }

        private string dzienTygodnia(DayOfWeek day)
        {
            switch (day)
            {
                case DayOfWeek.Friday:
                    return "Piątek";
                case DayOfWeek.Monday:
                    return "Poniedziałek";
                case DayOfWeek.Saturday:
                    return "Sobota";
                case DayOfWeek.Sunday:
                    return "Niedziela";
                case DayOfWeek.Thursday:
                    return "Czwartek";
                case DayOfWeek.Tuesday:
                    return "Wtorek";
                case DayOfWeek.Wednesday:
                    return "Środa";
            }
            return "";
        }

        // wpisuje dni tygodnia i nr tygodnia w roku
        private void uzupelnijKalendarz()
        {
            DateTime dzien;
            CultureInfo myCI = new CultureInfo("pl-PL");
            Calendar myCal = myCI.Calendar;

            foreach (DataGridViewRow r in nrWydanDataGridView.Rows)
            {
                dzien = Convert.ToDateTime(r.Cells["dATAWDataGridViewTextBoxColumn"].Value);
                r.Cells["dzienTygodniaColumn"].Value = dzienTygodnia(dzien.DayOfWeek);
                r.Cells["nrTygodniaColumn"].Value = myCal.GetWeekOfYear(dzien, CalendarWeekRule.FirstDay, DayOfWeek.Monday).ToString();
            }
        }

        private void generateNodes()
        {
            SqlCommand command = new SqlCommand();

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

            command.CommandText = "select ID_AGENCJI,Symbol from dbo.AGENCJE where aktywna = 1";

            command.Connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            TreeNode node;
            TreeNode node1;

            while (reader.Read())
            {
                node = new TreeNode(reader.GetValue(1).ToString());
                node1 = new TreeNode(reader.GetValue(1).ToString());
                node.Name = reader.GetValue(0).ToString();
                node1.Name = reader.GetValue(0).ToString();
                treeView3.Nodes.Add(node);
                treeView4.Nodes.Add(node1);
            }

            command.Connection.Close();
        }

        private void uprawnienia()
        {

            if (!User.getUser().St_kierownik)
            {
                infoTabControl.TabPages.Remove(grzbietyTabPage);
                infoTabControl.TabPages.Remove(planyProwizyjneTabPage);
                infoTabControl.TabPages.Remove(kosztyBiurTabPage);
                infoTabControl.TabPages.Remove(budzetTabPage);
            }
            
            if (!(User.getUser().St_kierownik | User.getUser().St_handlowiec | User.getUser().St_subhandlowiec | User.getUser().St_sekretarka)){
                infoTabControl.TabPages.Remove(kursyWalutTabPage);
                infoTabControl.TabPages.Remove(naWydanTab);
                infoTabControl.TabPages.Remove(agencjeTabPage);
            }

        

            dodajAgencjeButton.Enabled = User.getUser().St_kierownik;
            edytujAgencjeButton.Enabled = User.getUser().St_kierownik;
            dodajAgentaButton.Enabled = User.getUser().St_kierownik;
            edytujAgentaButton.Enabled = User.getUser().St_kierownik;
            dodajKontoButton.Enabled = User.getUser().St_kierownik;
            edytujKontoButton.Enabled = User.getUser().St_kierownik;

            nrWydanDataGridView.AllowUserToAddRows = User.getUser().St_kierownik;
            modulyDataGridView.AllowUserToAddRows = User.getUser().St_kierownik;

            bindingNavigatorAddNewItem2.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem3.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem5.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem6.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem7.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem8.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem9.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem10.Visible = User.getUser().St_kierownik | User.getUser().St_admin;

            zapiszGrzbietyToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszNrWydToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszTytultoolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszPromocjeToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            modulySaveToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszPlanProwToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszBudzetToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszKosztyBiuraToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;

            bindingNavigatorDeleteItem2.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem3.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem5.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem6.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem7.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem8.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem9.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem10.Visible = User.getUser().St_admin;
        }

       
        private void koszty_BiuraBindingSource_AddingNew(object sender, AddingNewEventArgs e)
        {            
            if (treeView3.SelectedNode != null)
            {
                DataView dataTableView = koszty_BiuraBindingSource.List as DataView;

                DataRowView rowView = dataTableView.AddNew();

                rowView["id_Agencji"] = treeView3.SelectedNode.Name;
              //  rowView["rok"] = DateTime.Today.Year;
              //  rowView["miesiac"] = DateTime.Today.Month;

                if (this.ostMs == 12)
                {
                    rowView["rok"] = ++this.ostRok;
                    rowView["miesiac"] = this.ostMs = 1;
                }
                else
                {
                    rowView["rok"] = this.ostRok;
                    rowView["miesiac"] = ++this.ostMs;
                } 
                e.NewObject = rowView;

                koszty_BiuraBindingSource.MoveLast();
            }
        }

        private void bUDZETBIURBindingSource_AddingNew(object sender, AddingNewEventArgs e)
        {
            if (treeView4.SelectedNode != null)
            {
                DataView dataTableView = bUDZETBIURBindingSource.List as DataView;

                DataRowView rowView = dataTableView.AddNew();

                rowView["ID_BIURA"] = treeView4.SelectedNode.Name;
                rowView["rok"] = DateTime.Today.Year;
                rowView["ms"] = DateTime.Today.Month;

                e.NewObject = rowView;

                bUDZETBIURBindingSource.MoveLast();
            }
        }

        private void podsumujKosztyBiura(){
            if (koszty_BiuraBindingSource.Current != null)
            {
                decimal suma = 0;
                decimal ksiegowosc = 0 ;
                decimal roznica = 0 ;

                DataRowView r = (DataRowView)koszty_BiuraBindingSource.Current;

                suma += r["czynsz"] == DBNull.Value ? 0 : Convert.ToDecimal(r["czynsz"]);
                suma += r["energia"] == DBNull.Value ? 0 : Convert.ToDecimal(r["energia"]);
                suma += r["telefony"] == DBNull.Value ? 0 : Convert.ToDecimal(r["telefony"]);
                suma += r["internet"] == DBNull.Value ? 0 : Convert.ToDecimal(r["internet"]);
                suma += r["parkingi"] == DBNull.Value ? 0 : Convert.ToDecimal(r["parkingi"]);
                suma += r["paliwo"] == DBNull.Value ? 0 : Convert.ToDecimal(r["paliwo"]);
                suma += r["place"] == DBNull.Value ? 0 : Convert.ToDecimal(r["place"]);
                suma += r["inne"] == DBNull.Value ? 0 : Convert.ToDecimal(r["inne"]);

                ksiegowosc = r["ksiegowosc"] == DBNull.Value ? 0 : Convert.ToDecimal(r["ksiegowosc"]);

                roznica = ksiegowosc - suma;

                razemLabel.Text = String.Format("{0:C}", suma);
                roznicaLabel.Text = String.Format("{0:C}", roznica);
            }
        }

        private void koszty_BiuraBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            podsumujKosztyBiura();
        }


        private void agencjeListBox_SelectedValueChanged(object sender, EventArgs e)
        {
            if (agencjeListBox.SelectedValue != null)
            {
                int idAgencji = Convert.ToInt32(agencjeListBox.SelectedValue);
                this.aGENCITableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCI, idAgencji);
                this.kONTATableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.KONTA, idAgencji);
                this.aGENCJETableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCJE, idAgencji);
                this.nowyAgentComboBox.DataSource = this.aGENCITableAdapter.GetDataByIdAgencjiAktywni(idAgencji);
                this.staryAgentComboBox.DataSource = this.aGENCITableAdapter.GetDataByNieaktywniIDAgencji(idAgencji);

                groupBox1.Enabled = User.getUser().St_kierownik & (idAgencji == User.getUser().IdAgencji);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if ((this.aGENCIBindingSource.Filter==null) || (this.aGENCIBindingSource.Filter == ""))
            {
                this.aGENCIBindingSource.Filter = "aktywny=1";
            }
            else
            {
                this.aGENCIBindingSource.Filter = "";
            }
        }

        private void dodajAgencjeButton_Click(object sender, EventArgs e)
        {
            AgencjaAddForm aaf = new AgencjaAddForm(0);

            if (aaf.ShowDialog() == DialogResult.OK)
            {
                agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            }
        }

        private void edytujAgencjeButton_Click(object sender, EventArgs e)
        {
            if (agencjeListBox.SelectedValue != null)
            {
                AgencjaAddForm aaf = new AgencjaAddForm((int)agencjeListBox.SelectedValue);
                if (aaf.ShowDialog() == DialogResult.OK)
                {
                    agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
                }
            }
        }

        private void dodajAgentaButton_Click(object sender, EventArgs e)
        {
            AgentAddForm aaf = new AgentAddForm(0, Convert.ToInt32(agencjeListBox.SelectedValue));

            if (aaf.ShowDialog() == DialogResult.OK)
            {
                aGENCITableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCI, Convert.ToInt32(agencjeListBox.SelectedValue));
                //agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            }
        }

        private void edytujAgentaButton_Click(object sender, EventArgs e)
        {
            if (aGENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)aGENCIBindingSource.Current;

                int id = Convert.ToInt32(row["ID_AGENTA"]);
                AgentAddForm aaf = new AgentAddForm(id, Convert.ToInt32(agencjeListBox.SelectedValue));
                if (aaf.ShowDialog() == DialogResult.OK)
                {
                    aGENCITableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.AGENCI, Convert.ToInt32(agencjeListBox.SelectedValue));
                }
            }
        }

        private void dodajKontoButton_Click(object sender, EventArgs e)
        {
            AddKontoForm aaf = new AddKontoForm(0, Convert.ToInt32(agencjeListBox.SelectedValue));

            if (aaf.ShowDialog() == DialogResult.OK)
            {

                kONTATableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.KONTA, Convert.ToInt32(agencjeListBox.SelectedValue));
                //agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            }
        }

        private void edytujKontoButton_Click(object sender, EventArgs e)
        {
            if (kONTABindingSource.Current != null)
            {
                DataRowView row = (DataRowView)kONTABindingSource.Current;

                int id = Convert.ToInt32(row["ID"]);
                AddKontoForm aaf = new AddKontoForm(id, Convert.ToInt32(agencjeListBox.SelectedValue));
                if (aaf.ShowDialog() == DialogResult.OK)
                {
                    kONTATableAdapter.FillByIdAgencji(this.sLOWNIKDataSet.KONTA, Convert.ToInt32(agencjeListBox.SelectedValue));
                }
            }
        }

        private void przepiszButton_Click(object sender, EventArgs e)
        {
            if ((staryAgentComboBox.SelectedValue == null) || (nowyAgentComboBox.SelectedValue == null))
            {
                MessageBox.Show("Wybierz symbole agentów");
                return;
            }

            this.Cursor = Cursors.WaitCursor;

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

            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "przepiszKlientow";

            command.Parameters.AddWithValue("@staryUserName", staryAgentComboBox.SelectedValue);
            command.Parameters.AddWithValue("@nowyUserName", nowyAgentComboBox.SelectedValue);

            command.Connection.Open();

            SqlTransaction transaction = command.Connection.BeginTransaction();
            command.Transaction = transaction;

            try
            {
                command.ExecuteNonQuery();
                transaction.Commit();
                MessageBox.Show("Klienci zostali przepisani.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType() + ex.Message);

                try
                {
                    transaction.Rollback();
                }
                catch (Exception ex2)
                {
                    MessageBox.Show("ROLLBACK:" + ex2.GetType() + ex.Message);
                }
            }

            command.Connection.Close();

            this.Cursor = Cursors.Default;

        }

        private void generujTytuly(){

            SLOWNIKDataSet.LISTA_TYTULOWDataTable dt = lISTA_TYTULOWTableAdapter.GetData()
                as SLOWNIKDataSet.LISTA_TYTULOWDataTable;
           
            foreach (SLOWNIKDataSet.LISTA_TYTULOWRow r in dt) {
                treeView1.Nodes.Add(new TreeNode(r.SYMB));
                treeView2.Nodes["wszystkieNode"].Nodes.Add(new TreeNode(r.SYMB));
                treeView2.Nodes["TylkoAktywne"].Nodes.Add(new TreeNode(r.SYMB)); 
            }
        }
   }
}