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

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

        public void BillingEngineCreated(MercatorUi.Engine.Gescom.BillingEngine BillingEngine)
        {
            BillingEngine.QtyChanged += BillingEngine_QtyChanged;
        }

        public void BillingEngineClosed(MercatorUi.Engine.Gescom.BillingEngine BillingEngine)
        {
            BillingEngine.QtyChanged -= BillingEngine_QtyChanged;
        }

        void BillingEngine_QtyChanged(object sender, MercatorUi.Engine.Gescom.BillingEngine.QtyChangedEventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            string s_id_base = "..."; // s_id van het artikel dat recht geeft op de promo
            string s_id_promo = "..."; // s_id van het artikel dat als promo wordt gegeven
            if (billingEngine.LignesVRecords[e.RowIndex].ID_ARTICLE != s_id_base)
                return;

            if ((e.QAfterChange > 10) && (e.QBeforeChange <= 10)) // de lijn met het promoartikel wordt toegevoegd
            {
                int n = billingEngine.AppendLine(billingEngine.LIGNES.Rows[e.RowIndex]);
                if (billingEngine.InsertItem(s_id_promo, billingEngine.LIGNES.Rows[n]))
                {
                    billingEngine.LignesVRecords[n].Q = e.QAfterChange - 10;
                    billingEngine.UpdateAmounts();
                }
            }
            else if ((e.QAfterChange > 10) && (e.QBeforeChange > 10)) // on utilise la ligne qui existe déjà
            {
                if ((e.RowIndex + 1 < billingEngine.LIGNES.Rows.Count) && (billingEngine.LignesVRecords[e.RowIndex + 1].ID_ARTICLE == s_id_promo))
                {
                    billingEngine.LignesVRecords[e.RowIndex + 1].Q = e.QAfterChange - 10;
                    billingEngine.UpdateAmounts();
                }
            }
            else if ((e.QAfterChange <= 10) && (e.QBeforeChange > 10)) // de bestaande lijn wordt verwijderd
            {
                if ((e.RowIndex + 1 < billingEngine.LIGNES.Rows.Count) && (billingEngine.LignesVRecords[e.RowIndex + 1].ID_ARTICLE == s_id_promo))
                {
                    billingEngine.LignesVRecords.RemoveAt(e.RowIndex + 1);
                    billingEngine.UpdateAmounts();
                }
            }
        }
    }
}