using System;
using System.Collections.Generic;
using System.Configuration;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Globalization;
using AjaxControlToolkit;

namespace bajaWare.Interfaces
{
    public partial class frmCatInterfaces : System.Web.UI.Page
    {
        public InterfacesService.IinterfacesServiceClient rsInterfaces = new InterfacesService.IinterfacesServiceClient();
       

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                if (!Page.IsPostBack)
                {
                    //this.SDS_Catalogos.SelectParameters[0].DefaultValue = idCatalogo;
                    this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
                    this.GV_Catalogos.AutoGenerateColumns = false;

                    BoundField ID = new BoundField();
                    ID.DataField = "intInterfaceid";
                    ID.HeaderText = "ID";
                    ID.HeaderStyle.Width = 45;
                    ID.ControlStyle.Width = 45;
                    BoundField Descripcion = new BoundField();
                    Descripcion.DataField = "vchInterface";
                    Descripcion.HeaderText = "Descripción";
                    Descripcion.HeaderStyle.Width = 800;
                    Descripcion.ControlStyle.Width = 800;
                    GV_Catalogos.Columns.Add(ID);
                    GV_Catalogos.Columns.Add(Descripcion);
                    GV_Catalogos.DataBind();

                }

                System.Threading.Thread.Sleep(0);
            }
            catch (Exception ex)
            {
                // mbox("OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString());
                Msg.Text = "OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString();
                UP_Msg.Update();
            }
        }


        protected void GV_Catalogos_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList dropDown = (DropDownList)sender;
            this.GV_Catalogos.PageSize = Int32.Parse(dropDown.SelectedValue);
            this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
            this.GV_Catalogos.DataBind();

        }


        protected void GV_Catalogos_RowCreated(Object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                HoverMenuExtender menu = new HoverMenuExtender();
                menu = (HoverMenuExtender)e.Row.FindControl("hoverMenu");
                e.Row.ID = e.Row.RowIndex.ToString();
                menu.TargetControlID = e.Row.ID;
            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                // Call the GetSortColumnIndex helper method to determine
                // the index of the column being sorted.
                int sortColumnIndex = GetSortColumnIndex();


            }

        }
        // This is a helper method used to determine the index of the
        // column being sorted. If no column is being sorted, -1 is returned.
        int GetSortColumnIndex()
        {

            // Iterate through the Columns collection to determine the index
            // of the column being sorted.
            foreach (DataControlField field in this.GV_Catalogos.Columns)
            {
                if (field.SortExpression == this.GV_Catalogos.SortExpression)
                {
                    return this.GV_Catalogos.Columns.IndexOf(field);
                }
            }

            return -1;
        }


        protected void GV_Catalogos_RowDataBound(Object sender, GridViewRowEventArgs e)
        {

           
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);

                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (e.Row.RowType == DataControlRowType.Header)
                    {
                        if (gridView.SortDirection == SortDirection.Ascending)
                        {
                            e.Row.Cells[cellIndex].CssClass = "sortascheaderstyle";

                        }
                        else
                        {
                            e.Row.Cells[cellIndex].CssClass = "sortdescheaderstyle";

                        }
                    }
                    else if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        if ((e.Row.RowIndex % 2) == 0)
                        {
                            e.Row.Cells[cellIndex].CssClass = "sortalternatingrowstyle";

                        }
                        else
                        {
                            e.Row.Cells[cellIndex].CssClass = "sortrowstyle";

                        }
                    }
                }
            }

            if (e.Row.RowType == DataControlRowType.Pager)
            {
                Label lblTotalNumberOfPages = (Label)e.Row.FindControl("lblTotalNumberOfPages");
                TextBox txtGoToPage = (TextBox)e.Row.FindControl("txtGoToPage");
                DropDownList ddlPageSize = (DropDownList)e.Row.FindControl("ddlPageSize");
                lblTotalNumberOfPages.Text = gridView.PageCount.ToString();
                txtGoToPage.Text = (gridView.PageIndex + 1).ToString();
                ddlPageSize.SelectedValue = gridView.PageSize.ToString();

            }


        }

        protected void GV_Catalogoss_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            if (e.NewPageIndex != -1) this.GV_Catalogos.PageIndex = e.NewPageIndex;
            this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
            this.GV_Catalogos.DataBind();
        }
        protected void GoToPage_TextChanged(object sender, EventArgs e)
        {
            TextBox txtGoToPage = (TextBox)sender;
            int pageNumber = Int32.Parse(txtGoToPage.Text);

            if (pageNumber > 0 && pageNumber <= this.GV_Catalogos.PageCount)
            {
                this.GV_Catalogos.PageIndex = pageNumber - 1;
                this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
                this.GV_Catalogos.DataBind();
            }
            else
            {
                this.GV_Catalogos.PageIndex = 0;
                this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
                this.GV_Catalogos.DataBind();
            }
        }

        protected void PopUpNuevo(object sender, EventArgs e)
        {
           
            dvDetalleCatalogo.DataSource = rsInterfaces.ListarInterfaces();
            dvDetalleCatalogo.DataBind();


            // Llama la fila del GridView de el sender para poder llamar al DataKey 
            Button btnDetails = (Button)sender;

            // Actualizamos el contenido en el panel de detalle
            this.updPnlCustomerDetail.Update();
            this.EditMSG.Visible = false;

            // Mostrando la ventana en forma modal
            this.mdlPopup.Show();

        }

        #region Guardar
        public void AlmacenaNuevo(Object sender, EventArgs e)
        {
            InterfacesService.Interfaces oInterfaces;
            InterfacesService.ServiceResult resultInterfaces = new InterfacesService.ServiceResult();
            int intInterfaceid = 0;
            try
            {
                oInterfaces = getInterfaceses();

                intInterfaceid = (int)getValorResult(rsInterfaces.InsertarInterfaces(oInterfaces));
                hdnInterfaces.Value = Convert.ToString(intInterfaceid);
                
                    // Invoca el Metodo Select del SDS_Catalogos
                    //GV_Catalogos.DataBind();
                    this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
                    GV_Catalogos.DataBind();

                    // Quita de la memorias
                    dvDetalleCatalogo.Dispose();

                    // Actualiza el Panel
                    updatePanel.Update();

                    // Invoca Metodo para Occultar Popup
                    mdlPopup.Hide();
                    this.Msg.Text = "REGISTRO No. " + intInterfaceid + " SE HA INGRESADO SATISFACTORIAMENTE.";
                    this.UP_Msg.Update();

                    // Actualiza el Panel
                    updPnlCustomerDetail.Update();

                    // Invoca Metodo para Occultar Popup
                    // this.mdlPopup.Hide();
               

            }
            catch (Exception ex)
            {
                Msg.Text = "OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString();
                UP_Msg.Update();
            }

        }


        private InterfacesService.Interfaces getInterfaceses()
        {

            InterfacesService.Interfaces oInterfaceses = null;


            TextBox vchInterfacesTxt = (TextBox)dvDetalleCatalogo.FindControl("vchInterfaces");
            try
            {
                oInterfaceses = new InterfacesService.Interfaces()
                {

                    vchInterface = Convert.ToString(vchInterfacesTxt.Text)
                };
            }
            catch (Exception ex) { throw ex; } return oInterfaceses;
        }


        private object getValorResult(InterfacesService.ServiceResult result)
        {
            object value = null;
            if (result.ServiceOk)
            {
                value = result.ResultValue;
            }
            else
            {
                throw new Exception(result.ErrorMessage);
            }
            return value;
        }
        // METODO QUE PERMITE VALIDAR CUALES DATOS SON OBLIGATORIOS PARA SU ALMACENAMIENTO
        [WebMethod]
        public static String ValidaDatos()
        {

            try
            {
                return "OK";
                
            }
            catch (Exception)
            {
                //TODO
                //FIX Msg.Text = "OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString();
                //mbox("OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString());
                //FIX UP_Msg.Update();
                return "NOK";
            }
        }

        #endregion
        #region Editar

        protected void BtnViewDetails_Click(object sender, EventArgs e)
        {
            try
            {

                Button btnDetails = (Button)sender;
                GridViewRow row = (GridViewRow)btnDetails.NamingContainer;

                int PintInterfaceid = Convert.ToInt32(this.GV_Catalogos.DataKeys[row.RowIndex][0]);

                this.dvEditaCatalogo.DataSource = rsInterfaces.EditarInterfaces(PintInterfaceid);
                this.dvEditaCatalogo.DataBind();

                dvEditaCatalogo.ChangeMode(DetailsViewMode.Insert);

                TextBox IDTXT = (TextBox)this.dvEditaCatalogo.FindControl("intInterfaceid");
                TextBox vchInterfacesTxt = (TextBox)this.dvEditaCatalogo.FindControl("vchInterfaces");



                foreach (InterfacesService.Interfaces ListaCampos in rsInterfaces.EditarInterfaces(PintInterfaceid))
                {

                    IDTXT.Text = Convert.ToString(ListaCampos.intInterfaceid);
                    vchInterfacesTxt.Text = ListaCampos.vchInterface;

                }


                if (this.dvEditaCatalogo.Fields.Count == 0)
                {
                    this.Button4.Visible = false;
                    this.lblAcepta_Detalle.Text = "MENSAJE DEL SISTEMA. EL REGISTRO FUE ELIMINADO POR OTRO USUARIO.";
                    this.lblAcepta_Detalle.Visible = true;
                }
                else
                {
                    this.Button4.Visible = true;
                    this.lblAcepta_Detalle.Text = "";
                    this.lblAcepta_Detalle.Visible = false;
                }


                this.UpdatePanel2.Update();

                // Actualizamos el contenido en el panel de detalle
                this.UpdatePanel1.Update();


                // Mostrando la ventana en forma modal
                this.mdlPopup2.Show();

            }
            catch (Exception ex)
            {
                this.Msg.Text = "OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString();
                this.UP_Msg.Update();
            }
        }

        public void ActualizaRegistro(Object sender, EventArgs e)
        {
            
            InterfacesService.Interfaces oInterfaces;
            InterfacesService.IinterfacesServiceClient InterfacesClient = new InterfacesService.IinterfacesServiceClient();
            InterfacesService.ServiceResult resultInterfaces = new InterfacesService.ServiceResult();


            try
            {
                oInterfaces = getEditarInterfaceses();

                getValorResult(InterfacesClient.ActualizarInterfaces(oInterfaces));
                hdnInterfaces.Value = Convert.ToString(oInterfaces.intInterfaceid);
                    

                Msg.Text = "REGISTRO " + oInterfaces.intInterfaceid + " ACTUALIZADO SATISFACTORIAMENTE";
                UP_Msg.Update();
                // INVOCA COMANDO UPDATE
                //SDS_Catalogos.Update();
                // REFRESCA GRID VIEW
                this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
                GV_Catalogos.DataBind();
                // ACTUALIZA PANEL
                updatePanel.Update();
                // INVOCA METODO PARA OCULTAR EL MODALBOX
                mdlPopup2.Hide();
            }
            catch (Exception ex)
            {
                Msg.Text = "OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString();
                UP_Msg.Update();
            }
        }

        private InterfacesService.Interfaces getEditarInterfaceses()
        {

            InterfacesService.Interfaces oInterfaceses = null;

            TextBox intInterfaceidTxt = (TextBox)this.dvEditaCatalogo.FindControl("intInterfaceid");
            TextBox vchInterfacesTxt = (TextBox)this.dvEditaCatalogo.FindControl("vchInterfaces");
            try
            {
                oInterfaceses = new InterfacesService.Interfaces()
                {

                    intInterfaceid = Convert.ToInt16(intInterfaceidTxt.Text),
                    vchInterface = Convert.ToString(vchInterfacesTxt.Text)
                };
            }
            catch (Exception ex) { throw ex; } return oInterfaceses;
        }

        #endregion

        #region Eliminar

        public void EliminaRegistro(Object sender, EventArgs e)
        {
            Button btnDetails = (Button)sender;
            GridViewRow row = (GridViewRow)btnDetails.NamingContainer;

            int PintInterfaceid = Convert.ToInt32(this.GV_Catalogos.DataKeys[row.RowIndex][0]);

            InterfacesService.IinterfacesServiceClient InterfacesClient = new InterfacesService.IinterfacesServiceClient();
            InterfacesService.ServiceResult resultInterfaces = new InterfacesService.ServiceResult();

            try
            {
                    getValorResult(InterfacesClient.BajaInterfaces(PintInterfaceid));
                    hdnInterfaces.Value = Convert.ToString(PintInterfaceid);
                

                Msg.Text = "REGISTRO " + PintInterfaceid + " ELIMINADO SATISFACTORIAMENTE";
                UP_Msg.Update();

                // REFRESCA GRID VIEW
                this.GV_Catalogos.DataSource = rsInterfaces.ListarInterfaces();
                GV_Catalogos.DataBind();

            }
            catch (Exception ex)
            {
                Msg.Text = "OCURRIO UN ERROR EN LA APLICACION ACTUAL, CONTACTE AL ADMINISTRADOR DEL SISTEMA " + ex.ToString();
                UP_Msg.Update();
            }
        }

        #endregion

    }
}