namespace Billing
{
    public class Customizer : MercatorUi.ICustomizers.IBillingEngineCreated, MercatorUi.ICustomizers.IBillingEngineClosed
    {

        public void BillingEngineCreated(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            billingEngine.BeforeBeforePaymentOrSave += billingEngine_BeforeBeforePaymentOrSave;
        }

        public void BillingEngineClosed(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            billingEngine.BeforeBeforePaymentOrSave -= billingEngine_BeforeBeforePaymentOrSave;
        }

        void billingEngine_BeforeBeforePaymentOrSave(object sender, MercatorUi.Engine.Gescom.BillingEngine.BeforeBeforePaymentOrSaveEventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            if (!billingEngine.LignesVRecords.Any(l => l.ID_ARTICLE == "PORT"))
            {
                int n = MercatorUi.Dialogs.AnswerYesNoCancel("Voulez-vous ajouter des frais de port ?");
                if (n == 3) // Cancel
                {
                    e.Cancel = true;
                    return;
                }
                if (n == 1) // Yes
                {
                    double port = MercatorUi.Dialogs.AskDouble("Montant frais de port ?", 10, "### ##0.00", true);
                    if (port == double.MinValue) // Cancel 
                    {
                        e.Cancel = true;
                        return;
                    }
                    int nLigne = billingEngine.AppendLine();
                    if (!billingEngine.InsertItem("PORT", billingEngine.LIGNES.Rows[nLigne], 1))
                    {
                        MercatorUi.Dialogs.Stop("Impossible d'ajouter les frais de port. " + billingEngine.LastError);
                        e.Cancel = true;
                        return;
                    }
                    billingEngine.LignesVRecords[nLigne].PU = port;
                    billingEngine.UpdateAmounts();
                }
            }
        }
    }
}