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

namespace MyNameSpace
{
    public class Class1 : MercatorUi.Interfaces.IExec
    {

        public void Main()
        {
            DataSet ds = Api.Zselect(MercatorUi.Globals.RepData, "select id,journal,piece,type from pieds_v where (journal='AboV')");
            if (ds == null)
                return;
            MercatorUi.Progress.ProgressCreate(ds.Tables[0].Rows.Count);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                using (MercatorUi.Engine.Gescom.BillingEngine billingEngine = MercatorUi.Engine.Gescom.BillingEngine.InitExisting(MercatorUi.Engine.Gescom.Billing.TypeVAEnum.V, Convert.ToInt32(dr["type"]), dr["id"].ToString().TrimEnd(), dr["journal"].ToString().TrimEnd(), Convert.ToInt64(dr["piece"])))
                {
                    if (billingEngine.DataSet == null)
                    {
                        MercatorUi.Dialogs.Stop(billingEngine.LastError);
                        billingEngine.Dispose();
                        return;
                    }
                    MercatorUi.Progress.ProgressIncrement(1);
                    var lignesTva16 = billingEngine.LignesVRecords.Where(l => l.TAUX_TVA.CompareTo(16, 2) == 0);
                    if (lignesTva16.Count() > 0)
                    {
                        foreach (MercatorDatabase.LIGNES_V l in lignesTva16)
                            l.TAUX_TVA = 17;
                        billingEngine.UpdateAmounts();
                        billingEngine.Save();
                    }
                }
            }
            MercatorUi.Progress.ProgressDestroy();
            MercatorUi.Dialogs.Stop("OK");
        }
    }
}