using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.IO;

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


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

                if (!Page.IsPostBack)
                {

                    dllLayout.DataSource = rscomboInter.ListarInterfaces();
                    dllLayout.DataBind();
                    clsUtilerias.cargaDropDownList((new InterfacesService.IinterfacesServiceClient()).ListarInterfaces(), "vchInterface", "intInterfaceid", ref dllLayout);


                }

                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.ListarBitacoraInterface();
            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.ListarBitacoraInterface();
            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.ListarBitacoraInterface();
                this.GV_Catalogos.DataBind();
            }
            else
            {
                this.GV_Catalogos.PageIndex = 0;
                this.GV_Catalogos.DataSource = rsInterfaces.ListarBitacoraInterface();
                this.GV_Catalogos.DataBind();
            }
        }

        protected void btnExportText_Click(object sender, EventArgs e)
        {
            if (GV_Catalogos.Rows.Count > 0)
            {
                Button btnDetails = (Button)sender;
                GridViewRow row = (GridViewRow)btnDetails.NamingContainer;

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

                //this.GV_Catalogos.DataSource = null;
                //this.GV_Catalogos.Columns.Clear();
                //this.GV_Catalogos.DataBind();

                //this.GV_Catalogos.DataSource = rsInterfaces.ListarBitacoraInterfaceID(PintInterfaceid);
                //this.GV_Catalogos.AutoGenerateColumns = false;

                InterfacesService.BitacoraInterfaces[] bit = rsInterfaces.ListarBitacoraInterfaceID(PintInterfaceid);

                //BoundField ID = new BoundField();
                //ID.DataField = "intBitDetID";
                //ID.HeaderText = "ID";
                //ID.HeaderStyle.Width = 45;
                //ID.ControlStyle.Width = 45;
                //BoundField Descripcion = new BoundField();
                //Descripcion.DataField = "Layout";
                //Descripcion.HeaderText = "Layout";
                //Descripcion.HeaderStyle.Width = 200;
                //Descripcion.ControlStyle.Width = 200;
                //BoundField Interface = new BoundField();
                //Interface.DataField = "Interface";
                //Interface.HeaderText = "Interface";
                //Interface.HeaderStyle.Width = 500;
                //Interface.ControlStyle.Width = 500;
                //BoundField Usuario = new BoundField();
                //Usuario.DataField = "Usuario";
                //Usuario.HeaderText = "Usuario";
                //Usuario.HeaderStyle.Width = 250;
                //Usuario.ControlStyle.Width = 250;
                //BoundField Fecha = new BoundField();
                //Fecha.DataField = "Fecha";
                //Fecha.HeaderText = "Fecha";
                //Fecha.HeaderStyle.Width = 50;
                //Fecha.ControlStyle.Width = 50;

                //GV_Catalogos.Columns.Add(ID);
                //GV_Catalogos.Columns.Add(Descripcion);
                //GV_Catalogos.Columns.Add(Interface);
                //GV_Catalogos.Columns.Add(Usuario);
                //GV_Catalogos.Columns.Add(Fecha);
                //GV_Catalogos.DataBind();


                System.IO.MemoryStream mstream = GetData(bit);

                string FileName = dllLayout.SelectedItem.Text;


                Session["GetData"] = null;
                Session["GetData"] = mstream;
                this.iframe.Attributes.Add("src", "../frmDescarga.aspx?nombre=" + FileName + PintInterfaceid + "&tipo=.txt");
                //Session["GetData"] = null;


            }
            else
            {

            }

        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Verifies that the control is rendered */
        }


        private MemoryStream GetData(InterfacesService.BitacoraInterfaces[] bit)
        {
            //Create the return memorystream object that will hold
            //the buffered data.
            MemoryStream ReturnStream = new MemoryStream();
            //Put together the connection strin

            List<string> str = new List<string>();
            try
            {

                //Create a streamwriter to write to the memory stream
                StreamWriter sw = new StreamWriter(ReturnStream);

                foreach (var item in bit.First().Interface.Split('\r'))
                {
                    sw.WriteLine(item);
                }

                sw.Flush();
                sw.Close();
            }


            catch (Exception Ex)
            {
                throw Ex;
            }
            ////Return the memory Stream
            return ReturnStream;
        }

        protected void ConsultaLayout_Click(object sender, EventArgs e)
        {
            //this.SDS_Catalogos.SelectParameters[0].DefaultValue = idCatalogo;
            String NegocioID = ddlNegocio.SelectedValue;
            int InterfaceID = Convert.ToInt32(dllLayout.SelectedValue);
            DateTime FechaCorte;
            if (this.FechaCorte.Text != "")
            {
                FechaCorte = Convert.ToDateTime(this.FechaCorte.Text);
            }
            else
            {
                FechaCorte = Convert.ToDateTime(DateTime.Now);
            }


            this.GV_Catalogos.DataSource = rsInterfaces.ListarBitacoraInterfaceLayout(NegocioID, InterfaceID, FechaCorte);
            this.GV_Catalogos.AutoGenerateColumns = false;


            //this.GV_Catalogos.Columns.Clear();

            if (this.GV_Catalogos.Columns.Count == 1)
            {
                BoundField ID = new BoundField();
                ID.DataField = "intBitDetID";
                ID.HeaderText = "ID";
                ID.HeaderStyle.Width = 45;
                ID.ControlStyle.Width = 45;
                BoundField Layout = new BoundField();
                Layout.DataField = "Layout";
                Layout.HeaderText = "Layout";
                Layout.HeaderStyle.Width = 500;
                Layout.ControlStyle.Width = 500;
                BoundField Usuario = new BoundField();
                Usuario.DataField = "Usuario";
                Usuario.HeaderText = "Usuario";
                Usuario.HeaderStyle.Width = 250;
                Usuario.ControlStyle.Width = 250;
                BoundField Fecha = new BoundField();
                Fecha.DataField = "Fecha";
                Fecha.HeaderText = "Fecha";
                Fecha.HeaderStyle.Width = 50;
                Fecha.ControlStyle.Width = 50;

                GV_Catalogos.Columns.Add(ID);
                GV_Catalogos.Columns.Add(Layout);
                GV_Catalogos.Columns.Add(Usuario);
                GV_Catalogos.Columns.Add(Fecha);

            }
            GV_Catalogos.DataBind();
        }

        protected void ddlNegocio_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlNegocio.SelectedValue != "0")
            {
                dllLayout.Enabled = true;
            }
            else
            {

                dllLayout.Enabled = false;
                ConsultaLayout.Enabled = false;
            }
        }

        protected void dllLayout_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dllLayout.SelectedValue != "------>")
            {
                FechaToma1_CalendarExtender.Enabled = true;
                FechaCorte.Enabled = true;
                ConsultaLayout.Enabled = true;

            }
            else
            {
                ddlNegocio.SelectedIndex = -1;
                dllLayout.Enabled = false;
                FechaToma1_CalendarExtender.Enabled = false;
                FechaCorte.Enabled = false;
                ConsultaLayout.Enabled = false;
            }
        }


    }
}