using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using MercatorApi;
using MercatorUi;

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

        public void BillingEngineClosed(MercatorUi.Engine.Gescom.BillingEngine BillingEngine)
        {
            BillingEngine.AfterInsertItem -= AfterInsertItem;
            BillingEngine.BeforePayment -= BeforePayment;
            BillingEngine.AfterSave -= AfterSave;
        }

        void AfterInsertItem(object sender, MercatorUi.Engine.Gescom.BillingEngine.AfterInsertItemEventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            if (e.LignesVRecord.S_CLE1 == "UTILBONCAD")
            {
                string id_boncad = Dialogs.AskString("Veuillez scanner le code barre", "", true, 35).Trim();
                if (id_boncad != "")
                {
                    int nbBoncad = billingEngine.LignesVRecords.Where(l => l.ID_BONCAD == id_boncad).Count();
                    if (nbBoncad == 0)
                    {
                        string reqSqlcad = "select count(*) as nbUtil, sum(q) as q, sum(pu) as pu from lignes_v where id_boncad=@id_boncad";
                        DataSet dscad = Api.Zselect(MercatorUi.Globals.RepData, reqSqlcad, new MercatorSqlParam("@id_boncad", id_boncad, SqlDbType.Char));
                        if (dscad != null)
                        {
                            if (Convert.ToInt16(dscad.Tables[0].Rows[0]["nbUtil"]) == 0)
                            {
                                Dialogs.Stop("Ce bon cadeau n'existe pas !");
                                e.CancelInsertItem = true;
                            }
                            else if (Convert.ToInt16(dscad.Tables[0].Rows[0]["nbUtil"]) > 1)
                            {
                                Dialogs.Stop("Ce bon cadeau a déjà été utilisé !");
                                e.CancelInsertItem = true;
                            }
                            else
                            {
                                e.LignesVRecord.Q = Convert.ToDouble(dscad.Tables[0].Rows[0]["q"]) * -1;
                                e.LignesVRecord.PU = Convert.ToDouble(dscad.Tables[0].Rows[0]["pu"]);
                                e.LignesVRecord.ID_BONCAD = id_boncad;
                            }
                        }
                        else
                        {
                            e.CancelInsertItem = true;
                        }
                    }
                    else
                    {
                        Dialogs.Stop("Ce bon cadeau a déjà été utilisé au sein de cette vente !");
                        e.CancelInsertItem = true;
                    }
                }
                else
                {
                    Dialogs.Stop("Code-Barres Vide !");
                    e.CancelInsertItem = true;
                }
            }
        }

        void BeforePayment(object sender, EventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            billingEngine.LignesVRecords.Where(l => l.S_CLE1 == "BONCAD").ToList().ForEach(l => l.ID_BONCAD = billingEngine.PiedsVRecord.ID + l.DL_ID);
        }

        void AfterSave(object sender, EventArgs e)
        {
            MercatorUi.Engine.Gescom.BillingEngine billingEngine = (MercatorUi.Engine.Gescom.BillingEngine)sender;
            if (billingEngine.LignesVRecords.Where(l => l.S_CLE1 == "BONCAD").Count() != 0)
            {
                DataSet ds = new DataSet();
                DataTable dt_lignes;
                DataTable dt_pieds;
                foreach (DataRow drBC in billingEngine.LIGNES.Select("S_CLE1='BONCAD'"))
                {
                    ds = new DataSet();
                    dt_lignes = new DataTable();
                    dt_lignes = billingEngine.LIGNES.Clone();
                    dt_lignes.ImportRow(drBC);
                    dt_pieds = new DataTable();
                    dt_pieds = billingEngine.PIEDS.Table.Clone();
                    dt_pieds.ImportRow(billingEngine.PIEDS);
                    ds.Tables.Add(dt_lignes);
                    ds.Tables.Add(dt_pieds);
                    ds.Tables.Add(Api.DataTableFromDico(MercatorUi.Globals.ParamIdentif, "ParamIdentif"));

                    /* Edit Layout
                    //string reportFileName = Globals.MainDir + "BonCadeau.repx";
                    string reportFileName = @"<MainDir\BonCadeau.repx";
                    string reportLayout = MercatorUi.Reporting.ReportingStatic.Reporting.EditLayout(Api.JustStem(reportFileName), Api.FileToStr(reportFileName, Encoding.UTF8), ds);
                    Api.StrToFile(reportLayout, reportFileName, Encoding.UTF8);
                    */
                    List<MercatorUi.Reporting.OutputDescriptor> listOutputDescriptors = new List<MercatorUi.Reporting.OutputDescriptor>();
                    // Preview
                    //listOutputDescriptors.Add(new MercatorUi.Reporting.OutputDescriptorPreview ());
                    //
                    listOutputDescriptors.Add(new MercatorUi.Reporting.OutputDescriptorPrint());
                    //MercatorUi.Reporting.ReportingStatic.Reporting.RunReport("BonCadeau", Globals.MainDir + "BonCadeau.repx", ds, listOutputDescriptors);
                    MercatorUi.Reporting.ReportingStatic.Reporting.RunReport("BonCadeau", @"<MainDir\BonCadeau.repx", ds, listOutputDescriptors);
                }
            }
        }
    }
}