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

// <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;

            // Lijst die de verschillende vennootschappen bevat waarnaar het Peppol-bericht kan worden overgedragen. De tweede parameter is de naam van de database.
            List<MercatorUi._BaseClasses.MercatorComboItem> l = new List<MercatorUi._BaseClasses.MercatorComboItem>
            {
                new MercatorUi._BaseClasses.MercatorComboItem("Company sa""MERCATORFIDUDEPEND"),
                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.IsConnected)
                    return;
                using (MercatorSqlCommand cmd = new MercatorSqlCommand(reqSql, conn))
                {
                    cmd.Parameters.AddWithValue("@id", guid);
                    if (!Api.SqlExec(conncmdunderTransactiontrue))
                        return;
                    grid.CurrentCell = null;
                    DataRow dataRowToRemove = peppolBoxForm.DataTable.RowsEnumerable().First(dr => dr["id"].Equals(guid));
                    peppolBoxForm.DataTable.Rows.Remove(dataRowToRemove);
                }
            }
        }
    }
}