using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MercatorApi;
using MercatorController;
using System.Windows.Forms;

namespace MercatorUi.MovableControls.ButtonsCodes
{
    public static class Script
    {

        public static void Exec(MercatorUi.MovableControls.MovableButton clickedButton)
        {
            // enter your customized code here
            MercatorUi.Forms.Inventory.InventoryForm inventoryForm = (MercatorUi.Forms.Inventory.InventoryForm)clickedButton.Form;
            if (!MercatorUi.Dialogs.AnswerYesNo(MercatorUi._Divers.Iif_langue(MercatorUi.Globals.Langue, "Add linked items ?", "Samengestelde artikels bijvoegen ?", "Ajouter les articles liés ?")))
                return;
            DataTable LIGNES_D = inventoryForm.InventoryEngine.LIGNES_D;
            MercatorUi.Progress.ProgressCreate(LIGNES_D.Rows.Count);
            foreach (DataRow dr in LIGNES_D.Select())
            {
                MercatorUi.Progress.ProgressIncrement(1);
                string id_art = dr["id_art"].ToString();
                if (id_art != "")
                {
                    DataSet ds = Api.Zselect(MercatorUi.Globals.RepData, "select id_lien,q from artliens where (id_art=@id_art) and (ven=1) order by suite", new MercatorSqlParam("@id_art", id_art, SqlDbType.Char));
                    if ((ds != null) && (ds.Tables[0].Rows.Count > 0))
                    {
                        Api.TrimEndDataSet(ds);
                        foreach (DataRow dr2 in ds.Tables[0].Rows)
                        {
                            int n = inventoryForm.InventoryEngine.AppendLine(true);
                            if (!inventoryForm.InventoryEngine.InsertItem(dr2["id_lien"].ToString(), LIGNES_D.Rows[n], Math.Round(Convert.ToDouble(dr["q"]) * Convert.ToDouble(dr2["q"]), MercatorUi.Globals.N_DEC_Q)))
                                MercatorUi.Dialogs.Stop(MercatorUi._Divers.Iif_langue(MercatorUi.Globals.Langue, "Unable to add : ", "Onmogelijk bij te voegen : ", "Impossible d'insérer : ") + dr2["id_lien"].ToString());
                        }
                    }
                }
            }
            inventoryForm.InventoryEngine.UpdateAmounts();
            MercatorUi.Progress.ProgressDestroy();
        }
    }
}