using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using Ionic.Zip;
using System.Drawing;

using System.Configuration;

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


        /// <summary>
        /// Propiedad que almacena el valor de las Fechas
        /// </summary>
        private DateTime[] Dias
        {
            get
            {
                return (DateTime[])ViewState["Dias"];
            }
            set
            {
                ViewState.Add("Dias", value);
            }
        }

        #region Calendario

        /// <summary>
        /// Llena dias del calendario
        /// </summary>
        public void LlenaDiasPagadosDataset()
        {
            try
            {
                DateTime primerFecha = new DateTime(calInterfaces.VisibleDate.Year, calInterfaces.VisibleDate.Month, 1);
                DateTime ultimaFecha = getPrimerDiaSigMes();
                Dias = rsInterfaceService.ListaFechasInterfaces(primerFecha.Date.ToString("yyyyMMdd"), ultimaFecha.Date.ToString("yyyyMMdd"));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public DateTime getPrimerDiaSigMes()
        {
            try
            {
                int Mes, Anio;
                if (calInterfaces.VisibleDate.Month == 12)
                {
                    Mes = 1;
                    Anio = calInterfaces.VisibleDate.Year + 1;
                }
                else
                {
                    Mes = calInterfaces.VisibleDate.Month + 1;
                    Anio = calInterfaces.VisibleDate.Year;
                }
                DateTime ultimaFecha = new DateTime(Anio, Mes, 1);
                return ultimaFecha;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        protected void calPagosRef_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
        {
            try
            {
                LlenaDiasPagadosDataset();
            }
            catch (Exception ex)
            {

            }
        }

        protected void calPagosRef_DayRender(object sender, DayRenderEventArgs e)
        {
            try
            {
                DateTime nextDate = new DateTime();
                if (Dias != null)
                {
                    foreach (var a in Dias)
                    {
                        nextDate = a;

                        // Marca dias 
                        if (nextDate.Date == e.Day.Date)
                        {
                            e.Cell.BackColor = Color.Blue;
                            e.Cell.ForeColor = Color.White;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //StackTrace st = new StackTrace(true);
                //clsLogging.registrarError(ex.Message, st, Session["User"].ToString());
                //wucMensajeSistema.setMensaje(ex.Message, 2);
            }
        }
        #endregion



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


                    CargaGrid(rsInterfaceService.ListarInterfaces());
                    calInterfaces.VisibleDate = DateTime.Now;
                    LlenaDiasPagadosDataset();
                }

            }
            catch (Exception ex)
            {
                Mensaje.setMensaje(ex.Message, 2);
            }
        }




        public void CargaGrid(InterfacesService.Interfaces[] lstInterfaces)
        {

            grvListaInterface.DataSource = lstInterfaces;
            grvListaInterface.DataBind();
            UPD_grvListaInterface.Update();
        }


        #region GridView


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvListaInterface_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridView gridView = (GridView)sender;

            if (e.Row.RowType == DataControlRowType.Header)
            {

            }
            // Body
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                if (e.Row.Cells[2].Text == "A")
                    e.Row.Cells[2].Text = "Individual-Empresarial";
                if (e.Row.Cells[2].Text == "I")
                    e.Row.Cells[2].Text = "Individual";
                if (e.Row.Cells[2].Text == "E")
                    e.Row.Cells[2].Text = "Empresarial";
            }

        }

        protected void grvListaInterface_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "go")
                {

                }
            }
            catch (Exception ex)
            {
                Mensaje.setMensaje(ex.Message, 2);
            }
        }

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


                string strIds = "";
                bool blArchivoGenerado = false;
                foreach (GridViewRow item in grvListaInterface.Rows)
                {
                    if (((CheckBox)item.FindControl("chkSelect")).Checked == true)
                        strIds += grvListaInterface.DataKeys[item.RowIndex][0].ToString() + "|";
                }

                if (!Directory.Exists(Server.MapPath("Tmp/")))
                    Directory.CreateDirectory(Server.MapPath("Tmp/"));

                InterfacesService.EjecutaInterface clsEje = new InterfacesService.EjecutaInterface();

                clsEje.strInterfaceIDs = strIds;
                clsEje.strUsuario = Session["User"] == null ? "" : Session["User"].ToString();
                clsEje.strFecha = txtFecha.Text.Split('/')[2] + txtFecha.Text.Split('/')[1] + txtFecha.Text.Split('/')[0];



                InterfacesService.ServiceResult result = rsInterfaceService.EjecutaInterfaces(clsEje);



                if (result.ServiceOk == true)
                {
                    InterfacesService.BitacoraInterfaces[] lstBit = rsInterfaceService.ListadoUltimoBitacoraLayout(strIds, clsEje.strFecha);


                    foreach (InterfacesService.BitacoraInterfaces item in lstBit)
                    {
                        blArchivoGenerado = true;
                        //System.IO.File.WriteAllText(Server.MapPath("Tmp/" + item.Layout + "_" + item.Negocio + ".txt"), item.Interface);
                        //System.IO.File.WriteAllLines(Server.MapPath("Tmp/" + item.Layout + "_" + item.Negocio + ".txt"), item.Interface.Split('\r'));
                        System.IO.File.WriteAllLines(Server.MapPath("Tmp/" + item.Layout + ".txt"), item.Interface.Split('\r'));


                        #region copia de archivo data access

                        string directorio = Repositorio;
                        string _dirLocal = Server.MapPath("Tmp/");

                        string nf = item.Layout + ".txt"; // rsInterfaceService.nombreArchivo(item.Layout + ".txt");
                        InterfacesService.ServiceResult _res = rsInterfaceService.almacenarArchivo(_dirLocal, @directorio, nf);

                        if (_res.ServiceOk == true)
                        {
                            //-----  Se crea mensaje
                            Mensaje.setMensaje(@"EL ARCHIVO SE ALMACENO SATISFACTORIAMENTE" ,1);// EN LA RUTA: " + directorio, 1);
                        }
                        else
                        {
                            Mensaje.setMensaje("NO SE ALMACENO EL ARCHIVO", 2); //EN LA RUTA. " + _res.ResultValue.ToString(), 2);
                        }

                        #endregion
                       

                    }

                    if (blArchivoGenerado)
                    {
                        //setArchivosZip("ArchZip.rar");
                        //btnExportText_Click(null, null);
                    }
                    else
                        ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "NoArch", "javascript:alert('No se generaron archivos');", true);

                    if (Directory.Exists(Server.MapPath("Tmp/")))
                        Directory.Delete(Server.MapPath("Tmp/"), true);
                }
                else
                    Mensaje.setMensaje(result.ErrorMessage, 2);

                Response.ContentType = "text/HTML";

                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OcultaProgreso", "javascript:TerminaProgreso();", true);


            }
            catch (Exception ex)
            {
                Mensaje.setMensaje(ex.Message, 2);
            }
        }
        #endregion



        private MemoryStream GetData()
        {
            //Create the return memorystream object that will hold
            //the buffered data.

            MemoryStream ReturnStream = new MemoryStream();
            //Put together the connection string

            try
            {

                FileStream inStream = File.OpenRead(Server.MapPath("Tmp/ArchZip.rar"));

                ReturnStream.SetLength(inStream.Length);
                inStream.Read(ReturnStream.GetBuffer(), 0, (int)inStream.Length);

                ReturnStream.Flush();
                inStream.Close();

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




        private void setArchivosZip(string strNameZip)
        {
            try
            {
                string strArchivo = string.Empty;

                using (ZipFile zip = new ZipFile())
                {
                    zip.AddDirectory(Server.MapPath("Tmp/"));
                    zip.Comment = "Interfaces BajaWare";
                    zip.Save(Server.MapPath("Tmp/") + strNameZip);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }



        protected void btnExportText_Click(object sender, EventArgs e)
        {
            Session["GetData"] = null;
            Session["GetData"] = GetData();
            this.iframe.Attributes.Add("src", "../frmDescarga.aspx?nombre=BajaWare&tipo=.zip");
            //Session["GetData"] = null;
        }

        #region Variables de conexión

        public string Repositorio
        {
            get
            {
                return ConfigurationManager.AppSettings["Repositorio"];
            }
        }

        public string Usuario
        {
            get
            {
                return ConfigurationManager.AppSettings["Usuario"];
            }
        }

        public string Clave
        {
            get
            {
                return ConfigurationManager.AppSettings["Clave"];
            }
        }

        public string AñoMes
        {
            get
            {
                return DateTime.Today.Year.ToString() + @"\" + DateTime.Today.Month.ToString() + @"\";
            }
        }

        #endregion


    }
}