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

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;
        }

        private const double minTot = 100;
        private const string id_art_promo = "PROM51JNJT";

        private void BillingEngine_BeforeBeforePaymentOrSave(object sender, MercatorUi.Engine.Gescom.BillingEngine.BeforeBeforePaymentOrSaveEventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            foreach (DataRow drLigne in billingEngine.LIGNES.RowsEnumerable(dr => dr["id_article"].Equals(id_art_promo)).ToArray())
            {
                billingEngine.LIGNES.Rows.Remove(drLigne);
            }
            billingEngine.UpdateAmounts();
            double totInitial = billingEngine.PiedsVRecord.TOT_TTC_DV;
            
            if (totInitial.CompareTo(minTot, billingEngine.NDec) > 0)
            {
                DataTable dtLignesCopy = billingEngine.LIGNES.Copy();
                bool PRIO_PV_changed = false;
                string PRIO_PV = MercatorUi.Globals.Params["PRIO_PV"];
                try
                {
                    if (PRIO_PV != "PROMOSOLDE")
                    {
                        MercatorUi.Globals.Params["PRIO_PV"] = "PROMOSOLDE";
                        PRIO_PV_changed = true;
                    }
                    billingEngine.BaremesVFilterKey = "MIN100";
                    billingEngine.ChangeAllPrices();
                }
                finally
                {
                    billingEngine.BaremesVFilterKey = null;
                    if (PRIO_PV_changed)
                        MercatorUi.Globals.Params["PRIO_PV"] = PRIO_PV;
                }

                double totPromo = Math.Round(totInitial - billingEngine.PiedsVRecord.TOT_TTC_DV, billingEngine.NDec);

                // remettre les valeurs initiales dans billingEngine.LIGNES
                foreach (DataRow dr in dtLignesCopy.Rows)
                {
                    DataRow drLigne = billingEngine.LIGNES.RowsEnumerable(p => p["dl_id"].Equals(dr["dl_id"])).First();
                    Api.DataRowMerge(drLigne, dr, false, new string[4] {"ID", "JOURNAL", "PIECE", "DL_ID" });
                }
                // ajouter une ligne promo le cas échéant
                if (totPromo.CompareTo(0d, billingEngine.NDec) > 0)
                {
                    int n = billingEngine.AppendLine();
                    if (!billingEngine.InsertItem(id_art_promo, billingEngine.LIGNES.Rows[n]))
                    {
                        MercatorUi.Dialogs.Stop(string.Format("Impossible d'ajouter l'article \"{0}\" !", id_art_promo));
                        e.Cancel = true;
                    }
                    billingEngine.LignesVRecords[n].DESIGNATIO = "Promo panier min. € " + minTot;
                    billingEngine.LignesVRecords[n].REMISE = 0;
                    billingEngine.LignesVRecords[n].REMISE2 = 0;
                    billingEngine.LignesVRecords[n].REMISE3 = 0;
                    billingEngine.LignesVRecords[n].REMISE4 = 0;
                    if (billingEngine.PiedsVRecord.REGIME == MercatorDatabase.RegimesEnum.Normal)
                        billingEngine.LignesVRecords[n].PU = -totPromo / (1 + (billingEngine.LignesVRecords[n].TAUX_TVA / 100));
                    else
                        billingEngine.LignesVRecords[n].PU = -totPromo;
                }
                billingEngine.UpdateAmounts();
            }
        }
    }
}