using Exferia_Aplicacion.Modelos_Informes;
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exferia_Informes.Informes
{
    public class Funciones_ImpresionDirecta : IDisposable
    {
        #region Variables privadas
        private INTERNO_Impresoras_DocumentoLocal_Modelo g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo = null;

        private int g_int_Indice_PaginaActual;
        private IList<Stream> g_ilst_Streams;

        #endregion

        public Funciones_ImpresionDirecta(INTERNO_Impresoras_DocumentoLocal_Modelo _mdl_INTERNO_Impresoras_DocumentoLocal_Modelo)
        {
            g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo = _mdl_INTERNO_Impresoras_DocumentoLocal_Modelo;
        }

        #region Funciones para Imprimir
        // Convertir repor a EMF (Enhanced Metafile) file.
        public void Convertir_Report_EMF(LocalReport _obj_LocalReport)
        {
            string str_InformacionDispositivo =
              @"<DeviceInfo>" +
                "<OutputFormat>EMF</OutputFormat>" +
                "<PageWidth>" + g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.Hoja_Ancho + "mm</PageWidth> " +
                "<PageHeight>" + g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.Hoja_Alto + "mm</PageHeight> " +
                "<MarginTop>0mm</MarginTop> " +
                "<MarginLeft>0mm</MarginLeft> " +
                "<MarginRight>0mm</MarginRight> " +
                "<MarginBottom>0mm</MarginBottom> " +
            "</DeviceInfo>";

            Warning[] arr_Warning;

            g_ilst_Streams = new List<Stream>();

            _obj_LocalReport.Render("Image", str_InformacionDispositivo, Crear_Secuncias, out arr_Warning);
            foreach (Stream stream in g_ilst_Streams)
            {
                stream.Position = 0;
            }
        }

        //Rutina para proporcionar al procesador de informes, para guardar una imagen para cada página del informe.
        private Stream Crear_Secuncias(string name,
                                        string fileNameExtension,
                                        Encoding encoding,
                                        string mimeType,
                                        bool willSeek)
        {
            Stream stream = new MemoryStream();
            g_ilst_Streams.Add(stream);
            return stream;
        }

        public void Imprimir(string _str_NombreDocumento)
        {
            if (g_ilst_Streams == null || g_ilst_Streams.Count == 0)
                throw new Exception("No hay ningun pagina");


            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings.PrinterName = g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.Nombre;

            if (!printDoc.PrinterSettings.IsValid)
            {
                throw new Exception("No hay ninguna impresora, seleccionada");
            }
            else
            {
                //A Color
                if (printDoc.PrinterSettings.SupportsColor)
                {
                    printDoc.DefaultPageSettings.Color = g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.Color;
                }

                // Seleccionar Bandeja
                if (g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.Bandeja_Numero > -1)
                {
                    printDoc.DefaultPageSettings.PaperSource = printDoc.PrinterSettings.PaperSources[g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.Bandeja_Numero];
                }

                // Doble Cara
                if (printDoc.PrinterSettings.CanDuplex)
                {
                    if (g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.DosCaras)
                    {
                        printDoc.PrinterSettings.Duplex = Duplex.Vertical;
                    }
                }

                printDoc.PrinterSettings.Copies = (short)(g_mdl_INTERNO_Impresoras_DocumentoLocal_Modelo.NumeroCopias);

                printDoc.DocumentName = _str_NombreDocumento;

                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                g_int_Indice_PaginaActual = 0;
                printDoc.Print();
            }

        }
        // Handler for PrintPageEvents
        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(g_ilst_Streams[g_int_Indice_PaginaActual]);

            // Adjust rectangular area with printer margins.
            Rectangle adjustedRect = new Rectangle(
                ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
                ev.PageBounds.Width,
                ev.PageBounds.Height);

            // Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect);

            // Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect);

            // Prepare for the next page. Make sure we haven't hit the end.
            g_int_Indice_PaginaActual++;
            ev.HasMorePages = (g_int_Indice_PaginaActual < g_ilst_Streams.Count);
        }
        #endregion

        public void Dispose()
        {
            if (g_ilst_Streams != null)
            {
                foreach (Stream stream in g_ilst_Streams)
                    stream.Close();
                g_ilst_Streams = null;
            }
        }
    }
}
