using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using MercatorApi;
using MercatorExtensions;
using MercatorUi;
using MercatorDatabase;
using System.Data.SqlClient;

// <CompileWithRoslyn />

namespace PeppolBox
{
    public class Customizer
    {
        public void TransferPeppolMessage(MercatorUi.GridPro.DataGridViewXPro grid, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            MercatorUi.Forms.Other.PeppolBoxForm peppolBoxForm = (MercatorUi.Forms.Other.PeppolBoxForm)grid.FindForm();
            Guid guid = (Guid)grid.Rows[e.RowIndex].Cells["id"].Value;

            // Liste qui va contenir les différentes sociétés vers lesquelles on peut transférer le message Peppol. Le second paramètre est le nom de la base de données.
            List<MercatorUi._BaseClasses.MercatorComboItem> l = new List<MercatorUi._BaseClasses.MercatorComboItem>
            {
                new MercatorUi._BaseClasses.MercatorComboItem("Company sa""MERCATORABC"),
                new MercatorUi._BaseClasses.MercatorComboItem("Company srl""MERCATORXYZ")
            };

            MercatorUi._Dialogs.DialogAskComboRet r = Dialogs.AskCombo("Transférer le message Peppol vers quel dossier ?", l, "Id");
            if (r == null)
                return;

            string reqSql = $@"
                declare @sql nvarchar(MAX) = replace(replace(dbo.LIST_COLUMNS('PEPPPOL_RECEIVED_MESSSAGES'),'dbo.',''),',IMPORTED_IN','')
                set @sql = 'insert into {r.Id}.dbo.PEPPPOL_RECEIVED_MESSSAGES (' + @sql + ') select ' + @sql + ' from PEPPPOL_RECEIVED_MESSSAGES where id=@id'
                EXECUTE sp_executesql @sql, N'@id UNIQUEIDENTIFIER', @id = @id
                delete from PEPPPOL_RECEIVED_MESSSAGES where id=@id".UnIndent(4);

            using (MercatorSqlConnection conn = new MercatorSqlConnection(Globals.RepData, true))
            {
                if (conn.Connection == null)
                    return;
                using (SqlTransaction transac = conn.Connection.BeginTransaction())
                using (SqlCommand cmd = new SqlCommand(reqSql, conn.Connection, transac))
                {
                    cmd.Parameters.AddWithValue("@id", guid);
                    if (!Api.SqlExec(cmd))
                    {
                        Api.SafeRollback(transac);
                        return;
                    }
                    transac.Commit();
                    grid.CurrentCell = null;
                    DataRow dataRowToRemove = peppolBoxForm.DataTable.RowsEnumerable().First(dr => dr["id"].Equals(guid));
                    peppolBoxForm.DataTable.Rows.Remove(dataRowToRemove);
                }
            }
        }
    }
}