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.Xml;

// <CompileWithRoslyn />

namespace PeppolBox
{
    public class Customizer : MercatorUi.ICustomizers.IPeppolBoxHelperCreated, MercatorUi.ICustomizers.IPeppolBoxHelperClosed
    {
        public void PeppolBoxHelperCreated(MercatorUi.Forms.Other.OtherClasses.PeppolBoxHelper peppolBoxHelper)
        {
            peppolBoxHelper.DataTable.Columns.Add("UserDefinedButtonColumnShowSigFou", typeof(string));

            foreach (var message in peppolBoxHelper.Messages.Where(m => m.IsInvoiceOrCreditNote).ToArray())
            {
                var parsedContent = message.ReceivedDoc.ParseContent(Globals.Langue, MercatorPeppol.ReceivedDoc.ParseContentEnum.WithSupplierName);
                if (!string.IsNullOrEmpty(parsedContent.Error))
                    continue;  // impossible de lire le message

                XmlNode nodeNumTva = parsedContent.XmlSelectNodes("cac:AccountingSupplierParty/cac:Party/cac:PartyTaxScheme/cbc:CompanyID").FirstOrDefault();
                if (string.IsNullOrEmpty(nodeNumTva?.InnerText))
                    continue; // le message ne contient pas le numéro de TVA du fournisseur

                List<string> fou = Api.Zselect<string>(Globals.RepData, "select f_id from FOU where f_num_tva=@num_tva", new MercatorSqlParam("@num_tva", nodeNumTva.InnerText, SqlDbType.Char));
                if ((fou == null) || !fou.Any())
                    continue; // Erreur SQL ou fournisseur non trouvé

                message.DataRow["UserDefinedButtonColumnShowSigFou"] = fou.First();
            }

            peppolBoxHelper.PeppolBoxForm.Grid.StandardColumnsCreated += Grid_StandardColumnsCreated;
        }

        public void PeppolBoxHelperClosed(MercatorUi.Forms.Other.OtherClasses.PeppolBoxHelper peppolBoxHelper)
        {
            peppolBoxHelper.PeppolBoxForm.Grid.StandardColumnsCreated -= Grid_StandardColumnsCreated;
        }

        private void Grid_StandardColumnsCreated(object sender, EventArgs e)
        {
            MercatorUi.GridPro.DataGridViewXPro grid = (MercatorUi.GridPro.DataGridViewXPro)sender;
            MercatorUi.Forms.Other.PeppolBoxForm peppolBoxForm = (MercatorUi.Forms.Other.PeppolBoxForm)grid.FindForm();
            grid.AddColumn(peppolBoxForm.DataTable.Columns["UserDefinedButtonColumnShowSigFou"], "Fou", columnWidth: 35);
        }
    }
}