using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data;
using Mercat_1.Empreses;
using Mercat_1.PdfCreator;
using System.Diagnostics;

namespace Mercat_1
{
    /// <summary>
    /// Lógica de interacción para Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        #region ViewModel
        sealed class ViewModel
            : INotifyPropertyChanged
        {
            #region INotifyPropertyChanged
            public event PropertyChangedEventHandler PropertyChanged;

            void SetField<X>(ref X field, X value, [CallerMemberName] string propertyName = null)
            {
                if (EqualityComparer<X>.Default.Equals(field, value)) return;

                field = value;

                var h = PropertyChanged;
                if (h != null) h(this, new PropertyChangedEventArgs(propertyName));
            }
            #endregion

            // Autocombobox Default settings
            //public IReadOnlyList<Person> Items
            //{
            //    get { return PersonModule.All; }
            //}

            Empresa selectedItem;
            public Empresa SelectedItem
            {
                get { return selectedItem; }
                set { SetField(ref selectedItem, value); }
            }

            long? selectedValue;
            public long? SelectedValue
            {
                get { return selectedValue; }
                set { SetField(ref selectedValue, value); }
            }
        }
        #endregion

        public Window1()
        {
            InitializeComponent();
            if (!FillComboBox())
            {
                DialogResult = false;
            }

        }

        #region Fillcombobox
        public bool FillComboBox()
        {
            bool success = true;
            try
            {
                DataTable dt = new DataTable();
                using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\source\\Mercat-1\\Mercatflor.accdb;Persist Security Info=True"))
                {
                    using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM empreses", connection))
                    {
                        da.Fill(dt);
                    }
                }
                //select new Empresa(Convert.ToUInt32(dr["Id"]), dr["Empresa"].ToString())).ToList();
                IReadOnlyList<Empresa> empresesList = (from DataRow dr in dt.Rows
                                                       select new Empresa(Convert.ToUInt32(dr["Id"]), Convert.ToUInt32(dr["numClient"]), dr["Empresa"].ToString())).ToList();
                llistaEmpreses.ItemsSource = empresesList;
            }
            catch (System.Data.OleDb.OleDbException oleError)
            {
                DisplayOleDbErrorCollection(oleError);
                success = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} Exception caught.", ex), "ERROR");
                success = false;
            }
            return success;
        }

        public void DisplayOleDbErrorCollection(OleDbException exception)
        {
            for (int i = 0; i < exception.Errors.Count; i++)
            {
                MessageBox.Show("Index #" + i + "\n" +
                       "Message: " + exception.Errors[i].Message + "\n" +
                       "Native: " + exception.Errors[i].NativeError.ToString() + "\n" +
                       "Source: " + exception.Errors[i].Source + "\n" +
                       "SQL: " + exception.Errors[i].SQLState + "\n");
            }
        }
        #endregion

        public Thickness DocumentMargin
        {
            get { return (Thickness)DataContext; }
            set { DataContext = value; }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            // Dialog box canceled
            DialogResult = false;
        }

        private void okButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(llistaEmpreses.Text.ToString()))
            {
                MessageBox.Show("El nombre de empresa esta vacio o no es correcto", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            bool saveresult = SaveDatatoDB();

            MypdfApp rere = new MypdfApp();
            SendToPrinter();

            string myMsg = "Combobox.Text: " + llistaEmpreses.Text + "\n" + string.Format("SelectedItem: {0} \n SelectedValue: {1}",llistaEmpreses.SelectedItem, llistaEmpreses.SelectedValue);
            MessageBoxResult result = MessageBox.Show(myMsg, "Resultados", MessageBoxButton.YesNoCancel);

            // Dialog box accepted
            //DialogResult = true;
        }

        private void SendToPrinter()
        {
            ProcessStartInfo info = new ProcessStartInfo();
            info.Verb = "print";
            info.FileName = @"E:\\source\\Mercat-1\\demo.pdf";
            info.CreateNoWindow = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;

            Process p = new Process();
            p.StartInfo = info;
            p.Start();

            p.WaitForInputIdle();
            System.Threading.Thread.Sleep(3000);
            if (false == p.CloseMainWindow())
                p.Kill();
        }

        #region SaveFormData

        private bool SaveDatatoDB()
        {
            bool success = true;

            /*
             * llistaempreses                           - Combobox amb el nom de l'empresa
             * data                                     - Data de l'operació
             * entrada_dc / sortida_dc                  - Entrades i sortides de carros DC
             * entrada_cc / sortida_cc                  - Entrades i sortides de carros CC+
             * entrada_tag5 / sortida_tag5              - Entrades i sortides de carros Tag5
             * entrada_safates / sortida_safates        - Entrades i sortides de Safates
             * entrada_alsacurta / sortida_alsacurta    - Entrades i sortides de alces curtes
             * entrada_alsallarga / sortida_alsallarga  - Entrades i sortides de alces llargues
             * Observacions                             - observacions de l'entrada
            */
            try
            {
                using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\source\\Mercat-1\\Mercatflor.accdb;Persist Security Info=True"))
                {
                    // Insertamos los datos del formulario en la tabla 'moviments' de la base de datos
                    connection.Open();

                    string queryInsertMovement = "INSERT INTO moviments (data, numClient, entrada_dc, entrada_cc, entrada_tag5, entrada_safates, entrada_alsacurta, entrada_alsallarga, observacions, sortida_dc, sortida_cc, sortida_tag5, sortida_safates, sortida_alsacurta, sortida_alsallarga)" +
                                                       " VALUES (@Data, '" + llistaEmpreses.SelectedValue.ToString() + "'," + entrada_dc.Text.ToString() + "," + entrada_cc.Text.ToString() + "," + entrada_tag5.Text.ToString() + "," +
                                                                entrada_safates.Text.ToString() + "," + entrada_alsacurta.Text.ToString() + "," + entrada_alsallarga.Text.ToString() + ",'" + Observacions.Text.ToString() + "'," +
                                                                sortida_dc.Text.ToString() + "," + sortida_cc.Text.ToString() + "," + sortida_tag5.Text.ToString() + "," + sortida_safates.Text.ToString() + "," +
                                                                sortida_alsacurta.Text.ToString() + "," + sortida_alsallarga.Text.ToString() + ")";
                    
                    using (OleDbCommand cmd = new OleDbCommand(queryInsertMovement, connection))
                    {
                        cmd.Parameters.Add("@Data", OleDbType.Date).Value = data.SelectedDate.Value.Date;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (InvalidOperationException inv)
                        {
                            MessageBox.Show(string.Format("{0} ", inv), "ERROR");
                        }
                        
                    }

                    // Buscamos en la tabla 'sumatori' si el cliente tiene registros
                    bool hasRecords = false;
                    bool canContinue = true;

                    int dbId = 0;
                    Int64 dbNumClient = (Int64)llistaEmpreses.SelectedValue;
                    int dbTotalDC = Int32.Parse(entrada_dc.Text) - Int32.Parse(sortida_dc.Text);
                    int dbTotalCC = Int32.Parse(entrada_cc.Text) - Int32.Parse(sortida_cc.Text);
                    int dbTotalTag = Int32.Parse(entrada_tag5.Text) - Int32.Parse(sortida_tag5.Text);
                    int dbTotalSafates = Int32.Parse(entrada_safates.Text) - Int32.Parse(sortida_safates.Text);
                    int dbTotalAlsaCurta = Int32.Parse(entrada_alsacurta.Text) - Int32.Parse(sortida_alsacurta.Text);
                    int dbTotalAlsaLlarga = Int32.Parse(entrada_alsallarga.Text) - Int32.Parse(sortida_alsallarga.Text);

                    string dbObservacions = string.Empty;
                    DateTime dbDataActualit;

                    string finalSqlQuery = string.Empty;

                    string queryBuscarCliente = string.Format("SELECT * FROM sumatori WHERE numClient = {0}", llistaEmpreses.SelectedValue);
                    using (OleDbDataAdapter da = new OleDbDataAdapter(queryBuscarCliente, connection))
                    {
                        try
                        {
                            DataTable dt = new DataTable();
                            da.Fill(dt);
                            if (dt != null)
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    dbId = dr.Field<int>("Id");
                                    dbNumClient = dr.Field<Int64>("numClient");
                                    dbDataActualit = dr.Field<DateTime>("data_actualitzacio");
                                    dbTotalDC += dr.Field<int>("total_dc");
                                    dbTotalCC += dr.Field<int>("total_cc");
                                    dbTotalTag += dr.Field<int>("total_tag5");
                                    dbTotalSafates += dr.Field<int>("total_safates");
                                    dbTotalAlsaCurta += dr.Field<int>("total_alsacurta");
                                    dbTotalAlsaLlarga += dr.Field<int>("total_alsallarga");
                                    dbObservacions = dr.Field<string>("observacions");
                                    hasRecords = true;
                                    //break;
                                }
                            }
                            else
                            {
                                canContinue = false;
                            }
                        }
                        catch (InvalidOperationException inv)
                        {
                            MessageBox.Show(string.Format("{0} ", inv), "ERROR");
                            canContinue = false;
                        }
                    }

                    if (canContinue)
                    {
                        dbDataActualit = DateTime.Now;

                        // si Observacions.text.lenght == 0 llavors "" sino afegim 
                        if (Observacions.Text.Length > 0) { dbObservacions += dbDataActualit.ToString() + " -> " + Observacions.Text + "\n"; };
                        
                        if (hasRecords)
                        {
                            // Update records
                            //dbObservacions += dbDataActualit.ToString() + " -> " + Observacions.Text + "\n";
                            finalSqlQuery = "UPDATE sumatori SET data_actualitzacio = '" + dbDataActualit.ToString() + "', total_dc = " + dbTotalDC.ToString() + ", total_cc = " + dbTotalCC.ToString() + 
                                ", total_tag5 = " + dbTotalTag.ToString() + ", total_safates = " + dbTotalSafates.ToString() + ", total_alsacurta = " + dbTotalAlsaCurta.ToString() + 
                                ", total_alsallarga = " + dbTotalAlsaLlarga.ToString() + ",observacions = '" + dbObservacions + "' WHERE numClient = " + llistaEmpreses.SelectedValue.ToString();
                        }
                        else
                        {
                            // Insert records
                            //dbObservacions = dbDataActualit.ToString() + " -> " + Observacions.Text + "\n";
                            finalSqlQuery = "INSERT INTO sumatori (numClient, data_actualitzacio, total_dc, total_cc, total_tag5, total_safates, total_alsacurta, total_alsallarga, observacions)" +
                                            " VALUES ('" + llistaEmpreses.SelectedValue.ToString() + "','" + dbDataActualit.ToString() + "'," + dbTotalDC.ToString() + "," + dbTotalCC.ToString() + "," +
                                                         dbTotalTag.ToString() + "," + dbTotalSafates.ToString() + "," + dbTotalAlsaCurta.ToString() + "," + dbTotalAlsaLlarga.ToString() + ",'" +
                                                         dbObservacions + "')";
                        }

                        using (OleDbCommand cmd = new OleDbCommand(finalSqlQuery, connection))
                        {
                            //cmd.Parameters.Add("@Data", OleDbType.Date).Value = dbDataActualit.ToString();
                            try
                            {
                                cmd.ExecuteNonQuery();
                            }
                            catch (InvalidOperationException inv)
                            {
                                MessageBox.Show(string.Format("{0} ", inv), "ERROR");
                            }

                        }

                    }
                    else
                    {
                        // ERROR
                        MessageBoxResult result = MessageBox.Show("Ha ocurrido un error mientras se obtenia datos de la base de datos.", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error );
                        success = false;
                    }

                    // 
                    connection.Close();
                }
            }
            catch (System.Data.OleDb.OleDbException oleError)
            {
                DisplayOleDbErrorCollection(oleError);
                success = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("{0} Exception caught.", ex), "ERROR");
                success = false;
            }
            return success;
        }
        #endregion

    }
}
