using System;
using System.Data;
using MercatorApi;
using MercatorUi;
using MercatorUi.Engine.Gescom;

namespace Billing
{
    public class CustomizerMercatorUi.ICustomizers.IBillingEngineCreated, MercatorUi.ICustomizers.IBillingEngineClosed
    {
        public void BillingEngineCreated(MercatorUi.Engine.Gescom.BillingEngine billingEngine)
        {
            billingEngine.BeforeBonCadeauAskVoucher += BillingEngine_BeforeBonCadeauAskVoucher;
        }

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

        private void BillingEngine_BeforeBonCadeauAskVoucher(object sender, BillingEngine.BeforeBonCadeauAskVoucherEventArgs e)
        {
            for (int i = 0; i <= 3; i++)
            {
                string idBon = Api.Ident();
                Api.LastError = "";
                var exists = Api.ZselectDirect(Globals.RepData, "if exists(select * from lignes_v where IDBONCADPAYTERM=@idBon) select 1 else select 0", new MercatorSqlParam("@idBon", idBon, SqlDbType.Char));
                if (!string.IsNullOrEmpty(Api.LastError))
                    Dialogs.Stop(Api.LastError);
                if (!Convert.ToBoolean(exists))
                {
                    e.IdBonCadeau = idBon;
                    break;
                }
                else if (i == 3)
                {
                    Dialogs.Stop("Cadeaubon: Unieke code wordt niet teruggevonden!");
                }
            }
        }
    }
}