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

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

        public static void Exec(MercatorUi.MovableControls.MovableButton clickedButton)
        {
            string s_id_famil = clickedButton.Form.DataSource.Rows[0]["s_id_famil"].ToString();
            if (s_id_famil == "")
            {
                Dialogs.Stop("Vous devez d'abord choisir une famille !");
                return;
            }

            string newSsFamilleLib = Dialogs.AskString(("Quelle nouvelle sous-famille ?"), "");
            if (string.IsNullOrEmpty(newSsFamilleLib))
                return;
            newSsFamilleLib = newSsFamilleLib.Trim();
            if (MercatorController.xFunctions.xLookUpString("SS_FAMIL", "NOM", newSsFamilleLib, "ID", string.Format("id_famille='{0}'", Api.UnquoteSql(s_id_famil))).TrimEnd() != "")
            {
                Dialogs.Stop("Cette sous-famille existe déjà !");
                return;
            }
            string newSsFamilleId = Api.Ident();
            using (SqlCommand cmd = new SqlCommand("insert into SS_FAMIL (id,nom,id_famille) values (@id,@nom,@id_famille)"))
            {
                cmd.Parameters.AddWithValue("id", newSsFamilleId).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("nom", newSsFamilleLib).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("id_famille", s_id_famil).SqlDbType = SqlDbType.Char;
                if (!Api.SqlExec(Globals.RepData, cmd))
                    return;
            }
            List<Control> l = clickedButton.Form.FindMovableControlsBySource("S_ID_SSFAM");
            if (l.Count > 0)
            {
                MovableControls.MovableComboBox combo = (MovableControls.MovableComboBox)l[0];
                BindingList<MercatorUi._BaseClasses.MercatorComboItem> l_familles = (BindingList<MercatorUi._BaseClasses.MercatorComboItem>)combo.DataSource;
                l_familles.Add(new MercatorUi._BaseClasses.MercatorComboItem(newSsFamilleLib, newSsFamilleId));
                combo.SelectedValue = newSsFamilleId;
            }

        }
    }
}