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;

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

        public static void Exec(MercatorUi.MovableControls.MovableButton clickedButton)
        {
            string newRayonLib = Dialogs.AskString(("Quel nouvel rayon ?"), "");
            if (string.IsNullOrEmpty(newRayonLib))
                return;
            newRayonLib = newRayonLib.Trim();
            if (MercatorController.xFunctions.xLookUpString("RAYONS", "NOM", newRayonLib, "ID").TrimEnd() != "")
            {
                Dialogs.Stop("Ce rayon existe déjà !");
                return;
            }
            string newRayonId = Api.Ident();
            using (SqlCommand cmd = new SqlCommand("insert into RAYONS (id,nom) values (@id,@nom)"))
            {
                cmd.Parameters.AddWithValue("id", newRayonId).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("nom", newRayonLib).SqlDbType = SqlDbType.Char;
                if (!Api.SqlExec(Globals.RepData, cmd))
                    return;
            }
            List<Control> l = clickedButton.Form.FindMovableControlsBySource("S_ID_RAYON");
            if (l.Count > 0)
            {
                MovableControls.MovableComboBox combo = (MovableControls.MovableComboBox)l[0];
                DataTable dt_rayons = (DataTable)combo.DataSource;
                DataRow dr_new = dt_rayons.NewRow();
                Api.DataRowResetContent(dr_new);
                dr_new["id"] = newRayonId;
                dr_new["nom"] = newRayonLib;
                dt_rayons.Rows.Add(dr_new);
                combo.SelectedValue = newRayonId;
            }

        }
    }
}