using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using MercatorApi;
using System.Windows.Forms;
using System.ComponentModel;


namespace MercatorUi.MovableControls.ButtonsCodes
{
    public static class Script
    {
        public static void Exec(MercatorUi.MovableControls.MovableButton clickedButton)
        {
            MercatorUi.Forms.Sig.SigForm sigForm = (MercatorUi.Forms.Sig.SigForm)clickedButton.Form;

            if (sigForm.StockRecord.S_GAMTYP1 == "")
            {
                Dialogs.Stop("Vous devez d'abord choisir un type de gamme !");
                return;
            }

            string newGamenum = Dialogs.AskString("Quel nouvel énuméré de gamme?", "");
            if (string.IsNullOrEmpty(newGamenum))
                return;
            newGamenum = newGamenum.Trim();
            if (MercatorController.xFunctions.xLookUpString("GAMENUM", "LIB", newGamenum, "ID", string.Format("id_type='{0}'", Api.UnquoteSql(sigForm.StockRecord.S_GAMTYP1))).TrimEnd() != "")
            {
                Dialogs.Stop("Ce énuméré existe déjà !");
                return;
            }
            string newGamenumId = Api.Ident();
            using (SqlCommand cmd = new SqlCommand("insert into GAMENUM (id,lib,id_type) values (@id,@lib,@id_type)"))
            {
                cmd.Parameters.AddWithValue("id", newGamenumId).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("lib", newGamenum).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("id_type", sigForm.StockRecord.S_GAMTYP1).SqlDbType = SqlDbType.Char;
                if (!Api.SqlExec(Globals.RepData, cmd))
                    return;
            }
            List<Control> l = clickedButton.Form.FindMovableControlsBySource("S_GAMENUM1");
            if (l.Count > 0)
            {
                MovableControls.MovableComboBox combo = (MovableControls.MovableComboBox)l[0];
                BindingList<MercatorUi._BaseClasses.MercatorComboItem> itemList = (BindingList<MercatorUi._BaseClasses.MercatorComboItem>)combo.DataSource;
                itemList.Add(new MercatorUi._BaseClasses.MercatorComboItem(newGamenum, newGamenumId));
                combo.SelectedValue = newGamenumId;
            }
        }
    }
}