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

namespace Billing
{
    public class Customizer : MercatorUi.ICustomizers.IBillingEngineCreated, MercatorUi.ICustomizers.IBillingEngineClosed
    {
        private const int nArt = 3;

        public void BillingEngineCreated(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            if (Globals.IsMercatorPenguinServer)
            {
                billingEngine.BeforeSave += new MercatorUi.Engine.Gescom.BillingEngine.BeforeSaveEventHandler(BillingEngine_BeforeSave);
                for (int i = 1; i <= nArt; i++)
                {
                    // retirer des lignes les articles précédemment saisis dans MercatorPenguin
                    foreach (DataRow dr in billingEngine.LIGNES.Select(string.Format("(dl_id='{0}')", Api.Replicate(i.ToString(), 10))))
                        billingEngine.LIGNES.Rows.Remove(dr);
                    // mettre 1 comme valeur par défaut pour les quantités
                    if (Convert.ToDouble(billingEngine.PIEDS["Q_ART" + i]).CompareTo(0, 2) == 0)
                        billingEngine.PIEDS["Q_ART" + i] = 1;
                }
            }
        }

        public void BillingEngineClosed(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            if (Globals.IsMercatorPenguinServer)
                billingEngine.BeforeSave -= new MercatorUi.Engine.Gescom.BillingEngine.BeforeSaveEventHandler(BillingEngine_BeforeSave);
        }

        void BillingEngine_BeforeSave(object sender, MercatorUi.Engine.Gescom.BillingEngine.BeforeSaveEventArgs e)
        {
            // ajouter dans les lignes les articles saisis en pied dans MercatorPenguin
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            for (int i = 1; i <= nArt; i++)
            {
                double q = Convert.ToDouble(billingEngine.PIEDS["Q_ART" + i]);
                if ((billingEngine.PIEDS["ID_ART" + i].ToString() != "") && (q.CompareTo(0, 2) != 0))
                {
                    int n = billingEngine.AppendLine();
                    if (!billingEngine.InsertItem(billingEngine.PIEDS["ID_ART" + i].ToString(), n, q))
                    {
                        e.CancelSave = true;
                        Globals.ApiLogDelegate.Invoke("Impossible d'ajouter l'article " + billingEngine.PIEDS["ID_ART" + i]); // écrire dans le log de MercatorPenguinServer
                        return;
                    }
                    billingEngine.LIGNES.Rows[n]["dl_id"] = Api.Replicate(i.ToString(), 10);
                }
            }
        }
    }
}