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

namespace Baza_Reklam
{
    public partial class FacturesForm : Form, IForm
    {
        private const string query = "SELECT TOP 2000 * FROM VIEW_ZESTAWIENIE_FAKTUR_STARE ";

        private static FacturesForm fakturesForm;
        private readonly SqlCommand command;
        private readonly SqlDataAdapter sqlDataAdapter;

        private bool commandExecuted;

        public static FacturesForm getFacturesForm(MDIBazaReklam parent)
        {
            if (fakturesForm == null){
                fakturesForm = new FacturesForm(parent);
            }
            return fakturesForm;
        }

        private FacturesForm(Form parent)
        {
            InitializeComponent();

            MdiParent = parent;

            //podmiana connstringa
            zestawienieFakturTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            reklamaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
         
            //obiekty wykorzytywane przy wyszukiwaniu
            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);
           
            command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.Connection = conn;
            
            sqlDataAdapter = new SqlDataAdapter();

            //ustawia domyslny rok i miesiąc w pasku wyszukiwania
            rokToolStripTextBox.Text = DateTime.Today.Year.ToString();
            miesiacToolStripTextBox.Text = DateTime.Today.Month.ToString();

            wyszukajToolStrip.Items.Insert(14, new ToolStripLabel("nieuregulowane:"));
            wyszukajToolStrip.Items.Insert(15, new ToolStripControlHost(new CheckBox(), "zalegleCheckBox"));
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).ThreeState = true;
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState = CheckState.Indeterminate;           
        }

        private void FacturesForm_Load(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Maximized;

            DBBindings.bindujGrzbiety2(grzbietToolStripComboBox);
            DBBindings.bindujAgencje(agencjaToolStripComboBox);
            DBBindings.bindujTytuly2(tytulToolStripComboBox);

            command.CommandText = query;
            sqlDataAdapter.SelectCommand = command;
        }

        //private void fakturyDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        //{
        //    zestawienieFakturBindingSource.CancelEdit();
        //}
        
        private void zamToolStripButton_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {              
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;

                if (row["reklamaId"] != DBNull.Value)
                {
                    int idRek = Convert.ToInt32(row["reklamaId"]);
                    
                    OrderDetails.getOrderDetails().pokazSzczegolyZamowienia(idRek);
                    OrderDetails.getOrderDetails().ShowDialog();

                    /*
                    OrderDetails od = new OrderDetails();
                    od.pokazSzczegolyZamowienia(idRek);
                    DialogResult result = od.ShowDialog();*/
                }
            }
        }

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

                if (row["reklamaId"] != DBNull.Value)
                {
                    int idRek = Convert.ToInt32(row["reklamaId"]);
                    Facturer f = new Facturer(idRek);
                    f.ShowDialog();
                }
            }
        }

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

                rEKLAMADataSet.ZestawienieFaktur.Clear();
                sqlDataAdapter.Fill(rEKLAMADataSet.ZestawienieFaktur);
                fakturyDataGridView.Refresh();

                Cursor = Cursors.Default;
            }
        }

        private void wyszukajToolStripButton_Click(object sender, EventArgs e)
        {
            wyszukajToolStrip.Visible = wyszukajToolStrip.Visible ? false : true;
        }

        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            command.CommandText = query;

            rEKLAMADataSet.ZestawienieFaktur.Clear();

            command.CommandText += " where 1=1 ";

            command.Parameters.Clear();

            if (nrFakturyToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(nrFakturyToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy numer faktury.");
                    return;
                }

                command.CommandText += " AND NUMER=@nr";
                command.Parameters.AddWithValue("@nr", nrFakturyToolStripTextBox.Text.Trim());
            }

            if (kodRozliczeniowyToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText += " AND NUMER_ROZ=@kod";
                command.Parameters.AddWithValue("@kod", kodRozliczeniowyToolStripTextBox.Text.Trim());
            }

            if (rokToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(rokToolStripTextBox.Text.Trim(), out i))
                {
                    MessageBox.Show("Podaj prawidłowy rok.");
                    return;
                }

                command.CommandText += " AND YEAR(DATA_SPRZEDAZY)=@rok";
                command.Parameters.AddWithValue("@rok", rokToolStripTextBox.Text.Trim());
            }

            if (miesiacToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(miesiacToolStripTextBox.Text.Trim(), out i))
                {
                    MessageBox.Show("Podaj prawidłowy miesiąc.");
                    return;
                }

                command.CommandText += " AND MONTH(DATA_SPRZEDAZY)=@miesiac";
                command.Parameters.AddWithValue("@miesiac", miesiacToolStripTextBox.Text.Trim());
            }

            if (agencjaToolStripComboBox.Text.Trim() != "")
            {
                command.CommandText += " AND Agencja=@agencja";
                command.Parameters.AddWithValue("@agencja", agencjaToolStripComboBox.Text.Trim());
            }
            
            if (((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState == CheckState.Checked)
            {
                command.CommandText += " AND (BRUTTO - suma_zaplat) > 0";
            }
            else if (((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState == CheckState.Unchecked)
            {
                command.CommandText += " AND (BRUTTO - suma_zaplat) <= 0 ";
            }

            if (((ComboBox)grzbietToolStripComboBox.Control).SelectedItem != null)
            {
                command.CommandText += " AND (GRZBIET = @grzbiet) ";
                command.Parameters.AddWithValue("@grzbiet", (((BoundItem)(grzbietToolStripComboBox.SelectedItem)).IDEvalue1));
            }

            if (tytulToolStripComboBox.SelectedItem != null)
            {
                command.CommandText += " AND (ID_TYTUL= @tytul) ";
                command.Parameters.AddWithValue("@tytul", ((BoundItem)tytulToolStripComboBox.SelectedItem).IDEvalue1);
            }

            //MessageBox.Show(command.CommandText + nrFakturyToolStripTextBox.Text);
            sqlDataAdapter.SelectCommand = command;

            Cursor = Cursors.WaitCursor;

            sqlDataAdapter.Fill(rEKLAMADataSet.ZestawienieFaktur);
            commandExecuted = true;

            Cursor = Cursors.Default;
        }

        private void kryteriumWyszukiwania_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13) szukajToolStripButton.PerformClick();
        }

        /// <summary>
        /// Podsumowuje brutto i zaplate z wyswietlonych faktur
        /// </summary>
        private void podsumuj() {

            if (zestawienieFakturBindingSource.List.Count != 0)
            {
            decimal brutto = Convert.ToDecimal(rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(BRUTTO)",""));
            decimal netto = Convert.ToDecimal(rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(netto)", ""));

            bruttoTextBox.Text = String.Format("{0:C}", brutto);
            nettoTextBox.Text = String.Format("{0:C}", netto);
            }
            else
            {
            bruttoTextBox.Clear();
            nettoTextBox.Clear();            
            }
        }

        private void zestawienieFakturBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {          
           podsumuj();
        }

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

        private void wyczyscPolaToolStripButton_Click(object sender, EventArgs e)
        {
            rEKLAMADataSet.ZestawienieFaktur.Clear();

            nrFakturyToolStripTextBox.Clear();
            kodRozliczeniowyToolStripTextBox.Clear();
            rokToolStripTextBox.Clear();
            miesiacToolStripTextBox.Clear();
            agencjaToolStripComboBox.SelectedIndex = -1;
            agencjaToolStripComboBox.Text = "";
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState = CheckState.Indeterminate;
            grzbietToolStripComboBox.SelectedIndex = -1;
            grzbietToolStripComboBox.Text = "";

            tytulToolStripComboBox.SelectedIndex = -1;
        }

        private void wplataToolStripButton_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;
                REKLAMADataSet.ZestawienieFakturRow fakt =
                    (REKLAMADataSet.ZestawienieFakturRow)row.Row;

                if (!fakt.IsreklamaIdNull())
                {
                    PaymentForm p = new PaymentForm(fakt.reklamaId);
                    p.ShowDialog();
                }
            }
        }

        private void podgladToolStripButton_Click(object sender, EventArgs e)
        {
            //nic nie zaznaczono
            if (zestawienieFakturBindingSource.Current == null) return;

            DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;

            //nie faktury, wiec nie ma co podgladnac albo mamy do czynienia z nowa faktura
            if (row["id_faktury"] == DBNull.Value || row["reklamaId"] == DBNull.Value) return;

            Cursor = Cursors.WaitCursor;

            int idFaktury = Convert.ToInt32(row["id_faktury"]);

            FactureViewer fv = new FactureViewer(idFaktury, false, 0);
            fv.ShowDialog();

            Cursor = Cursors.Default;
        }

        /// <summary>
        /// Przechodzi do okna KLIENCI i wyświetla dane klienta związanego z  fakturą.
        /// </summary>
        private void klientToolStripButton_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;

                int custID = Convert.ToInt32(row["ID_NABYWCY"]);

                ClientsForm.getClientsForm((MDIBazaReklam)MdiParent).pokazKlienta(custID);

                Hide();

                ClientsForm.getClientsForm((MDIBazaReklam)MdiParent).Show();

            }   
        }

        private void FacturesForm_Shown(object sender, EventArgs e)
        {
            if (User.Instance().IsKierownik)
            {
                agencjaToolStripComboBox.Text = User.Instance().SymbolAgencji;
            }
            else if (User.Instance().IsHandlowiec)
            {
                kodRozliczeniowyToolStripTextBox.Text = User.Instance().Kod_agenta;
            }            
        }

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

            ExcelHelper ex = new ExcelHelper();
            ex.Export(fakturyDataGridView);

            Cursor = Cursors.Default;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;
                REKLAMADataSet.ZestawienieFakturRow fakt =
                    (REKLAMADataSet.ZestawienieFakturRow)row.Row;

                if (!fakt.IsidWplatyNull())
                {
                    PaymentForm2 p = new PaymentForm2(fakt.idWplaty, fakt.ID_FAKTURY);
                    p.ShowDialog();
                }
            }
        }

        #region IForm Members

        public void CloseForm()
        {
            fakturesForm = null;
        }

        #endregion
    }
}