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;


namespace MercatorUi.MovableControls.ButtonsCodes
{
    public static class Script
    {
        const int catNo = 1;

        public static void Exec(MercatorUi.MovableControls.MovableButton clickedButton)
        {
            MercatorUi.Forms.Sig.SigForm sigForm = (MercatorUi.Forms.Sig.SigForm)clickedButton.Form;
            string catTb = sigForm.Sig.Module == MercatorUi.Sig._SigEnum.STOCK ? "CAT_STCK" : "CAT_" + sigForm.Sig.Module;

            string newCatLib = Dialogs.AskString((string.Format("Welke nieuwe categorie {0} {1} ?", catNo, sigForm.Sig.Caption[MercatorUi.Globals.Langue])), "");
            if (string.IsNullOrEmpty(newCatLib))
                return;
            newCatLib = newCatLib.Trim();
            if (MercatorController.xFunctions.xLookUpString(catTb, "NOM", newCatLib, "ID", "type=" + catNo).TrimEnd() != "")
            {
                Dialogs.Stop("Deze categorie bestaat al!");
                return;
            }
            string newCatId = Api.Ident();
            using (SqlCommand cmd = new SqlCommand(string.Format("insert into {0} (id,nom,type) values (@id,@nom,@type)", catTb)))
            {
                cmd.Parameters.AddWithValue("id", newCatId).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("nom", newCatLib).SqlDbType = SqlDbType.Char;
                cmd.Parameters.AddWithValue("type", catNo);
                if (!Api.SqlExec(Globals.RepData, cmd))
                    return;
            }
            List<Control> l = clickedButton.Form.FindMovableControlsBySource("S_CAT" + catNo);
            if (l.Count > 0)
            {
                MovableControls.MovableComboBox combo = (MovableControls.MovableComboBox)l[0];
                System.ComponentModel.BindingList<MercatorUi._BaseClasses.MercatorComboItem> itemList = (System.ComponentModel.BindingList<MercatorUi._BaseClasses.MercatorComboItem>)combo.DataSource;
                itemList.Add(new MercatorUi._BaseClasses.MercatorComboItem(newCatLib, newCatId));
                combo.SelectedValue = newCatId;
            }
        }
    }
}