using C1.Web.Wijmo.Controls.C1GridView;
using System;
using System.Data;
using System.Web.UI;

namespace GridView_Dialog_Sample
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }

        private void BindGrid()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("PARAM");
            dt.Columns.Add("VALUE");
            dt.Rows.Add("1", "Timeout", "30");
            dt.Rows.Add("2", "RetryCount", "3");

            ConfigurationParamGrid.DataSource = dt;
            ConfigurationParamGrid.DataBind();
        }

        protected void ImageButtonEdit_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        {
            // Redirect to the shared logic
            OpenDialogFromCommand(e.CommandName, e.CommandArgument);
        }

        protected void ConfigurationParamGrid_RowCommand(object sender, C1GridViewCommandEventArgs e)
        {
            // Redirect to the shared logic
            OpenDialogFromCommand(e.CommandName, e.CommandArgument);
        }

        // Shared helper to handle the data loading and script registration
        private void OpenDialogFromCommand(string commandName, object commandArgument)
        {
            if (commandName == "EditDetraction" || commandName == "edit")
            {
                int rowIndex = Convert.ToInt32(commandArgument);

                // Accessing the grid via its ID since we are in the same page
                if (ConfigurationParamGrid.DataKeys != null && ConfigurationParamGrid.DataKeys.Count > rowIndex)
                {
                    // 1. Populate data from DataKeys
                    lblParamName.Text = ConfigurationParamGrid.DataKeys[rowIndex].Values["PARAM"].ToString();
                    txtParamValue.Text = ConfigurationParamGrid.DataKeys[rowIndex].Values["VALUE"].ToString();
                    ViewState["ID"] = ConfigurationParamGrid.DataKeys[rowIndex].Values["ID"].ToString();

                    // 2. Prepare the Script
                    // We use RegisterStartupScript which is safer for Wijmo initialization
                    string script = $"OpenEditParamWindow('{EditConfigurationParamWindow.ClientID}', 'Editing {lblParamName.Text}');";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "PopUp", script, true);
                }
            }
        }

        protected void ConfigurationParamGrid_RowEditing(object sender, C1GridViewEditEventArgs e)
        {

        }
    }
}