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
    {
        public void CreateActionFromPeppolMessage(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;

            List<bool> l = Api.Zselect<bool>(MercatorUi.Globals.RepData, "if exists(select * from ACTIONS where entryid=@id) select cast(1 as bit) as ret else select cast(0 as bit) as ret", new MercatorSqlParam("@id", guid.ToString(), SqlDbType.Char));
            if (l == null)
                return;
            if (l[0])
            {
                MercatorUi.Dialogs.Stop("Ce message est déjà inclus dans une action du CRM !");
                return;
            }

            MercatorUi.Forms.Other.OtherClasses.PeppolBoxHelper.PeppolMessage message = peppolBoxForm.PeppolBoxHelper.Messages.First(m => m.Id == guid);
            if (!message.IsInvoiceOrCreditNote)
                return;
            MercatorPeppol.ReceivedDoc.ParseContentRet parsedContent = message.ReceivedDoc.ParseContent(Globals.Langue, MercatorPeppol.ReceivedDoc.ParseContentEnum.WithSupplierName | MercatorPeppol.ReceivedDoc.ParseContentEnum.WithPdf);
            if (!string.IsNullOrWhiteSpace(parsedContent.Error))
            {
                MercatorUi.Dialogs.Stop(string.Format("Parsing message {0} : {1}", message.Id, parsedContent.Error));
                return;
            }

            int n = MercatorUi.Dialogs.Answer3Buttons("Créer une action du CRM avec ce message ?", "Gescom", "Compta", Api.Iif_langue(MercatorUi.Globals.Langue, IifLangueEnum.Cancel));
            if (n == 3)
                return; // Cancel

            MercatorUi.Engine.Crm.Tools.ActionDescriptor actionCreated;
            string id_actempl = n == 1 ? ".A-0RFCEXW" : ".A-KC6V639";
            using (MercatorUi.Engine.Crm.ActionEngine actionEngine = MercatorUi.Engine.Crm.ActionEngine.InitNew(MercatorUi.Sig._SigEnum._none, null, id_actempl))
            {
                if (actionEngine == null)
                {
                    MercatorUi.Dialogs.Stop("ActionEngine.InitNew : " + actionEngine.LastError);
                    return;
                }
                if (actionEngine.ReadOnly)
                {
                    MercatorUi.Dialogs.Stop("ActionEngine.InitNew : engine is ReadOnly!");
                    return;
                }

                actionEngine.ActionsRecord.OBJET = (message.ReceivedDoc.ChangeType == "INVOICE_RECEIVED" ? "Facture" : "Note de crédit") + " Peppol de " + parsedContent.SupplierName;
                actionEngine.ActionsRecord.ENTRYID = message.Id.ToString();
                actionEngine.ActionsRecord.MOMENT_2 = message.Moment;
                actionEngine.ActionsRecord.MOMENT_1 = message.Moment.AddDays(5);

                if (!actionEngine.Save())
                {
                    MercatorUi.Dialogs.Stop(string.Format("Erreur lors de la sauvegarde de l'action : {0}", actionEngine.LastError));
                    return;
                }
                else if (parsedContent.Pdf == null)
                {
                    MercatorUi.Dialogs.Stop("Pas de PDF dans le message");
                }
                else
                {
                    if (!Api.BytesToSqlFile(parsedContent.Pdf, Api.AddBS(actionEngine.SqlFileViewDefaultDirectory) + "PeppolDoc.pdf"))
                        MercatorUi.Dialogs.Stop("Impossible de joindre le PDF à l'action");
                }
                actionCreated = new MercatorUi.Engine.Crm.Tools.ActionDescriptor(actionEngine);
            }
            MercatorUi.Globals.Main.ShowActionExisting(actionCreated.Id, actionCreated.Module, actionCreated.IdSig);
        }
    }
}