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

// <CompileWithRoslyn />

namespace Billing
{
    public class Customizer : MercatorUi.ICustomizers.IBillingEngineCreated, MercatorUi.ICustomizers.IBillingEngineClosed
    {
        public void BillingEngineCreated(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            billingEngine.GettingPricingByQty += BillingEngine_GettingPricingByQty;
        }

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

        private void BillingEngine_GettingPricingByQty(object sender, MercatorUi.Engine.Gescom.BillingEngine.GettingPricingByQtyEventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            double totQ = billingEngine.LignesVRecords.Where(l => l.ID_ARTICLE == e.LigneVRecord.ID_ARTICLE).Sum(l => l.Q);
            if (totQ.CompareTo(e.Q, Globals.N_DEC_Q) != 0)
            {
                e.Q = totQ;
                MercatorUi.Engine.Gescom.BillingEngine.AfterApplyPricingInfoEventHandler afterApplyPricingInfoEventHandler = null;
                afterApplyPricingInfoEventHandler = (s, e2) =>
                {
                    billingEngine.AfterApplyPricingInfo -= afterApplyPricingInfoEventHandler;
                    if (e.DataRowLignes == e2.DataRowLignes) // zitten we nog steeds op dezelfde lijn?
                    {
                        // update de andere lijnen met hetzelfde artikel
                        foreach (var l in billingEngine.LignesVRecords.Where(l => (l.ID_ARTICLE == e.LigneVRecord.ID_ARTICLE) && (l.DataRow != e.DataRowLignes)))
                        {
                            l.PU = e.LigneVRecord.PU;
                            l.REMISE = e.LigneVRecord.REMISE;
                        }
                    }
                };
                billingEngine.AfterApplyPricingInfo += afterApplyPricingInfoEventHandler;
            }
        }
    }
}