using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using ExportFaktur.EXPODataSetTableAdapters;
using ExportFaktur.CDNDataSetTableAdapters;

namespace ExportFaktur
{
    public partial class ExportForm : Form
    {
        private ExpoToCDNExport ex = new ExpoToCDNExport();

        KLIENCITableAdapter klientAdapter = new KLIENCITableAdapter();
        FAKTURA_DETAILSTableAdapter fakturyDetailsAdapter = new FAKTURA_DETAILSTableAdapter();
        
        KontrahenciTableAdapter kontrahenciAdapter = new KontrahenciTableAdapter();
        TraElemTableAdapter TraElemAdapter = new TraElemTableAdapter();
        TraNagTableAdapter TraNagAdapter = new TraNagTableAdapter();
        TraVatTableAdapter TraVatAdapter = new TraVatTableAdapter();

        SqlConnection conn = new SqlConnection(ConnString.CDNConnection);
        SqlConnection bazaReklamConn = new SqlConnection(ConnString.BazaReklamConnection);

        int nMaxProgress;
        
        public ExportForm()
        {
            InitializeComponent();

            ex.CDNDataset = new CDNDataSet();

            klientAdapter.ClearBeforeFill = true;
            fakturyDetailsAdapter.ClearBeforeFill = true;

            fAKTURYTableAdapter.Connection = bazaReklamConn;
            klientAdapter.Connection = bazaReklamConn;
            fakturyDetailsAdapter.Connection = bazaReklamConn;

            kontrahenciAdapter.Connection = conn;
            TraNagAdapter.Connection = conn;
            TraElemAdapter.Connection = conn;
            TraVatAdapter.Connection = conn;
        }

        private void ExportForm_Load(object sender, EventArgs e)
        {
            RefreshView();
        }

        private void RefreshView()
        {
            fAKTURYTableAdapter.FillByNotExported(eXPODataSet.FAKTURY);

            statusLabel1.Text = "Liczba faktur " + eXPODataSet.FAKTURY.Count;

            nMaxProgress = eXPODataSet.FAKTURY.Count;
            
            toolStripProgressBar1.Value = 0;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            dataGridView1.EndEdit();
            dataGridView1.Refresh();
            
            if (backgroundWorker1.IsBusy)
            {
                return;
            }

            if (fAKTURYBindingSource.List.Count == 0)
            {
                return;
            }

            backgroundWorker1.RunWorkerAsync();

            
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int n = 0;
            
            conn.Open();
            
            foreach (EXPODataSet.FAKTURYRow row in eXPODataSet.FAKTURY.Rows)
            {
                if (!backgroundWorker1.CancellationPending)
                {                   
                    
                    if (row.Exportuj)
                    {
                        SqlTransaction transaction = conn.BeginTransaction();

                        kontrahenciAdapter.AttachTransaction(transaction);
                        TraNagAdapter.AttachTransaction(transaction);
                        TraElemAdapter.AttachTransaction(transaction);
                        TraVatAdapter.AttachTransaction(transaction);

                        try
                        {
                            klientAdapter.FillByCustomerId(eXPODataSet.KLIENCI, Convert.ToInt32(row["id_nabywcy"]));
                            fakturyDetailsAdapter.FillByIdFaktury(eXPODataSet.FAKTURA_DETAILS, Convert.ToInt32(row["id_faktury"]));

                            ex.DodajKlienta(eXPODataSet.KLIENCI[0]);
                            kontrahenciAdapter.Update(ex.CDNDataset.Kontrahenci);

                            decimal sumaNetto = eXPODataSet.sumaNETTO();
                            decimal vat = eXPODataSet.stawkaVAT();
                            decimal rabat = eXPODataSet.rabatProcent();

                            ex.DodajNaglowekFaktury(row, ex.CDNDataset.Kontrahenci[0], sumaNetto, vat, rabat);
                            ex.DodajElementyFaktury(eXPODataSet.FAKTURA_DETAILS, ex.CDNDataset.TraNag[0]);
                            ex.DodajVAT(ex.CDNDataset.TraNag[0], sumaNetto, vat);

                            TraNagAdapter.Update(ex.CDNDataset.TraNag);
                            TraElemAdapter.Update(ex.CDNDataset.TraElem);
                            TraVatAdapter.Update(ex.CDNDataset.TraVat);

                            transaction.Commit();
                            row.EXPORTED = true;
                            row.EXPORTED_DATA = DateTime.Now;
                            fAKTURYTableAdapter.Update(row);

                            n++;
                            backgroundWorker1.ReportProgress(n);
                        }
                        catch (Exception exception)
                        {
                            transaction.Rollback();

                            //Send Email
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.AppendLine("Wyjatek przy imporcie faktury o id: " + row.ID_FAKTURY);
                            stringBuilder.AppendLine("Szczegoly:");
                            stringBuilder.AppendLine(exception.ToString());

                            conn.Close();
                            bazaReklamConn.Close();

                            EmailSender.Send(stringBuilder.ToString());

                            throw;
                        }
                        finally
                        {
                            eXPODataSet.KLIENCI.Clear();
                            eXPODataSet.FAKTURA_DETAILS.Clear();
                            ex.CDNDataset.TraVat.Clear();
                            ex.CDNDataset.TraElem.Clear();
                            ex.CDNDataset.TraNag.Clear();
                            ex.CDNDataset.Kontrahenci.Clear();
                        }
                    }
                }
                else
                {
                    conn.Close();
                    e.Cancel = true;               
                }
            }

            if (bazaReklamConn.State == ConnectionState.Open)
            {
                bazaReklamConn.Close();
            }
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
                  
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!Visible || WindowState != FormWindowState.Normal)
            {
                return;
            }
            
            if (toolStripProgressBar1.Maximum != nMaxProgress)
            {
                toolStripProgressBar1.Maximum = nMaxProgress;
            }

            if (e.ProgressPercentage < toolStripProgressBar1.Maximum)
            {
                toolStripProgressBar1.Value = e.ProgressPercentage;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {            
            if (e.Cancelled)
            {
                statusLabel1.Text = "Export faktur anulowany";
                MessageBox.Show("Export faktur anulowany");
            }
            else if (e.Error != null)
            {
                statusLabel1.Text = "Wystąpił błąd.";
                MessageBox.Show("Wystąpił błąd: " + e.Error.Message);
            }
            else
            {
                toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
                statusLabel1.Text = "Export faktur zakończony";
                MessageBox.Show("Export faktur zakończony");
            }

            RefreshView();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {                
                backgroundWorker1.CancelAsync();
            }
        }

        private void refreshToolStripButton_Click(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
            {
                RefreshView();
            }
        }

        private void ExportForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                return;
            }
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void cbSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            cbSelectAll.Text = cbSelectAll.Checked ? "Odznacz wszystko" : "Zaznacz wszystko";

            foreach (EXPODataSet.FAKTURYRow row in eXPODataSet.FAKTURY.Rows)
            {
                row.Exportuj = cbSelectAll.Checked;
            }
        }
    }
}