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_rayon = clickedButton.Form.DataSource.Rows[0]["s_id_rayon"].ToString();
            if (s_id_rayon == "")
            {
                Dialogs.Stop("U moet eerst een rayon selecteren!");
                return;
            }

            string newFamilleLib = Dialogs.AskString(("Welke nieuwe familie?"), "");
            if (string.IsNullOrEmpty(newFamilleLib))
                return;
            newFamilleLib = newFamilleLib.Trim();
            if (MercatorController.xFunctions.xLookUpString("FAMILIES", "NOM", newFamilleLib, "ID", string.Format("id_rayon='{0}'", Api.UnquoteSql(s_id_rayon))).TrimEnd() != "")
            {
                Dialogs.Stop("Deze familie bestaat al!");
                return;
            }
            string newFamilleId = Api.Ident();
            using (SqlCommand cmd = new SqlCommand("insert into FAMILLES (id,nom,id_rayon) values (@id,@nom,@id_rayon)"))
            {
                cmd.Parameters.AddWithValue("id", newFamilleId).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("nom", newFamilleLib).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("id_rayon", s_id_rayon).SqlDbType = SqlDbType.Char;
                if (!Api.SqlExec(Globals.RepData, cmd))
                    return;
            }
            List<Control> l = clickedButton.Form.FindMovableControlsBySource("S_ID_FAMIL");
            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(newFamilleLib, newFamilleId));
                combo.SelectedValue = newFamilleId;
            }

        }
    }
}