using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySqlConnector;
using System.Data;
using DevExpress.Web;
using System.Collections;

//
// Nota : Per colpa di un bug in mySQL Connector .Net v6.10.6 non si può usare SqlDataSource e bisogna gestire le operazioni CRUD a mano! (la soluzione sarebbe di aggiornare MySql Connector all'ultima versione !)
//
namespace OlympiaIntranet
{
    public partial class ElencoProxy : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                Response.Redirect("~/SignIn.aspx");
            }

            CommonClass.SetColumnFilterContains(gvElencoProxy);

            RefreshGrid();

        }

        protected void RefreshGrid()
        {
            MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.mySqlConnection);
            MySqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "select * from olympia_proxylist";
            conn.Open();

            MySqlDataReader dataReader = cmd.ExecuteReader();
            var dataTable = new DataTable();
            dataTable.Load(dataReader);
            conn.Close();

            gvElencoProxy.DataSource = dataTable;
            gvElencoProxy.KeyFieldName = "IDProxylist";
            gvElencoProxy.DataBind();
        }

        protected void gvElencoProxy_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            // ref link : https://www.devexpress.com/Support/Center/Question/Details/KA18686/aspxgridview-how-to-implement-crud-operations-with-a-custom-data-source

            ASPxGridView gridView = (ASPxGridView)sender;
            IDictionaryEnumerator enumerator = e.NewValues.GetEnumerator();
            string sqlKey = String.Empty;
            string sqlValue = String.Empty;
            string sql = String.Empty;
            string cod_tit_originale = String.Empty;
            enumerator.Reset();
            int cont = 1;
            while (enumerator.MoveNext())
            {

                if (enumerator.Key.ToString() == "cod_tit_originale") { if (enumerator.Value != null) cod_tit_originale = enumerator.Value.ToString(); }

                if (cont == 7) // sono 7 i campi che salviamo : cod_tit_originale,isin_originale,descrizione_originale,cod_tit_proxy,isin_proxy,descrizione_proxy,scadenza
                {
                    sqlKey += enumerator.Key.ToString();
                    if (enumerator.Value != null)  sqlValue += "'" + Convert.ToDateTime(enumerator.Value).ToString("yyyy-MM-dd")+"'"; // Ultimo campo è scadenza che è una data
                    else sqlValue += "'2000-01-01'";
                }
                else
                {
                    sqlKey += enumerator.Key.ToString() + ",";
                    if (enumerator.Value != null) sqlValue += "'" + enumerator.Value.ToString() + "',";
                    else sqlValue += "NULL,";
                }
                cont++;
            }
            sql = "INSERT INTO olympia_proxylist (" + sqlKey + ",data_ins) values (" + sqlValue + ",CURDATE())";

            // Verifico che isin_originale non sia già presente fra le proxy, e nel caso segnalo errore e non permetto l'inserimento! (31/01/2024)
            List<string> listIsinOriginale = new List<string>();
            for (int i = 0; i < gvElencoProxy.VisibleRowCount; i++)
            {
                listIsinOriginale.Add(gvElencoProxy.GetRowValues(i, "cod_tit_originale").ToString());
            }
            if (listIsinOriginale.Contains(cod_tit_originale) == true)
            {
                e.Cancel = false;
                throw new MyException($"Titolo {cod_tit_originale} già presente nelle proxy, cancellarlo oppure modificarlo!");
            }

            // Salva nuovo Proxy in tabella olympia_proxylist
            MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.mySqlConnection);
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            gridView.CancelEdit();
            e.Cancel = true;

            RefreshGrid();
        }

        protected void gvElencoProxy_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // ref link : https://www.devexpress.com/Support/Center/Question/Details/KA18686/aspxgridview-how-to-implement-crud-operations-with-a-custom-data-source

            ASPxGridView gridView = (ASPxGridView)sender;
            int ID = (int)e.Keys[0];

            IDictionaryEnumerator enumerator = e.NewValues.GetEnumerator();
            string sqlKeyValue = String.Empty;
            string sql = String.Empty;
            enumerator.Reset();
            int cont = 1;
            while (enumerator.MoveNext())
            {
                if (cont == 7) // sono 7 i campi che salviamo : cod_tit_originale,isin_originale,descrizione_originale,cod_tit_proxy,isin_proxy,descrizione_proxy,scadenza
                {
                    if (enumerator.Value != null) sqlKeyValue += enumerator.Key.ToString()+"='" + Convert.ToDateTime(enumerator.Value).ToString("yyyy-MM-dd") + "',"; // Ultimo campo è scadenza che è una data
                    else sqlKeyValue += enumerator.Key.ToString() + "='2000-01-01',";
                    sqlKeyValue += "data_mod=CURDATE()";
                }
                else
                {
                    if (enumerator.Value != null) sqlKeyValue += enumerator.Key.ToString() + "='" + enumerator.Value.ToString() + "',";
                    else sqlKeyValue += enumerator.Key.ToString() + "=NULL,";
                }
                cont++;
            }
            sql = "UPDATE olympia_proxylist SET " + sqlKeyValue +" WHERE IDProxylist=" + ID;

            // Salva nuovo Proxy in tabella olympia_proxylist
            MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.mySqlConnection);
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            gridView.CancelEdit();
            e.Cancel = true;

            RefreshGrid();
        }

        protected void gvElencoProxy_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            // ref link : https://www.devexpress.com/Support/Center/Question/Details/KA18686/aspxgridview-how-to-implement-crud-operations-with-a-custom-data-source

            ASPxGridView gridView = (ASPxGridView)sender;
            int ID = (int)e.Keys[0];

            string sql = String.Empty;

            sql = "DELETE FROM olympia_proxylist WHERE IDProxylist=" + ID;

            // Salva nuovo Proxy in tabella olympia_proxylist
            MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.mySqlConnection);
            MySqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();

            gridView.CancelEdit();
            e.Cancel = true;

            RefreshGrid();
        }
    }
}