using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;

namespace Baza_Reklam
{
    public partial class OrderViewer : Form
    {
        private int reklamaId;
        DataSet ds;

        public OrderViewer(int idRek)
        {
            InitializeComponent();
            reklamaId = idRek;
                     
            ds = new DataSet();

            zamowienieTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Baza_Reklam.Raporty.zamowienie.xml");
            ds.ReadXml(s);
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("zamowienie", zamowienieTableAdapter.GetDataByReklamaId(reklamaId)));

            
            SqlCommand cm = new SqlCommand();
            cm.Connection = new SqlConnection();
            cm.CommandText = "declare @test varchar(800); set @test = ''; declare @nr_wyd int; " +
                " DECLARE kur2 CURSOR FOR SELECT [Nr Wydania] FROM [UKAŻE SIĘ W NR] WHERE (ReklamaId = @param) order by [Nr Wydania];" +
                " OPEN kur2; FETCH NEXT from kur2 into @nr_wyd; while @@fetch_status=0 begin   set @test  = @test + ', ' + CAST(@nr_wyd AS varchar); " +
                " fetch next from kur2 into @nr_wyd; end CLOSE kur2; DEALLOCATE kur2; select @test; ";
            cm.Parameters.AddWithValue("@param", reklamaId);
            cm.Connection.ConnectionString = ConnString.getConnString().Value;

            string emisje;
            cm.Connection.Open();
            emisje = (string)cm.ExecuteScalar();
            cm.Connection.Close();

            raporty r = new raporty();

            raporty.emisjeRow row = r.emisje.NewemisjeRow();
            row.ID = emisje;
            r.emisje.AddemisjeRow(row);

            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("raporty_emisje", r.emisje)); 
                       
            //this.reportViewer1.Print += new CancelEventHandler(HandlePrint);

            jezykComboBox.SelectedIndex = 0;

        }

        public OrderViewer(int idZam, int a)
        {
            InitializeComponent();
            reklamaId = idZam;

            ds = new DataSet();

            zamowienie2TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            reportViewer1.LocalReport.ReportEmbeddedResource = "Baza_Reklam.Raporty.zamowienie2.rdlc";
       
            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Baza_Reklam.Raporty.zamowienie.xml");
            ds.ReadXml(s);
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));
            raporty.Zamowienie2DataTable t= zamowienie2TableAdapter.GetDataByIdZamowienia(idZam);
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("zamowienie2", t));
            //this.reportViewer1.Print += new CancelEventHandler(HandlePrint);

           
            jezykComboBox.SelectedIndex = 0;

        }

        private void OrderViewer_Load(object sender, EventArgs e)
        {
            this.reportViewer1.RefreshReport();
        }

        // drukowanie
       
        /*
        private int m_currentPageIndex;
        private IList<Stream> m_streams;


        public void HandlePrint(object sender, CancelEventArgs e)
        {
           Run();
           //MessageBox.Show("Drukowanie");
           e.Cancel = true;
        }

        private void Print(PrinterSettings printerSettings)
        {
            if (m_streams == null || m_streams.Count == 0)
                return;

            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings = printerSettings;
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            printDoc.Print();
        }

        private void Run()
        {
            PrintDialog printDialog = new PrintDialog();
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                Export(reportViewer1.ServerReport);
                m_currentPageIndex = 0;
                Print(printDialog.PrinterSettings);
            }
        }

        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);
            
            // Note: Coordinate (0,0) does not coincide with the top left corner of
            // the page; it coincides with the top left corner of the printable area
            // of the page. To account for this we have to subtract the hard margin.

            RectangleF adjustedRect = new RectangleF(
                ev.PageBounds.Left - ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - ev.PageSettings.HardMarginY,
                ev.PageBounds.Width, ev.PageBounds.Height);
            
            ev.Graphics.DrawImage(pageImage, adjustedRect);
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);

        }

        private void Export(ServerReport report)
        {
            string deviceInfo =

              "<DeviceInfo>" +

              "  <OutputFormat>EMF</OutputFormat>" +

              "  <PageWidth>21cm</PageWidth>" +

              "  <PageHeight>29cm</PageHeight>" +

              "  <MarginTop>1cm</MarginTop>" +

              "  <MarginLeft>1.5cm</MarginLeft>" +

              "  <MarginRight>1.5cm</MarginRight>" +

              "  <MarginBottom>1cm</MarginBottom>" +

              "</DeviceInfo>";
            
            m_streams = new List<Stream>();
            string mimeType;
            string extension;
            System.Collections.Specialized.NameValueCollection urlAccessParameters = new System.Collections.Specialized.NameValueCollection();
            urlAccessParameters.Add("rs:PersistStreams", "True");
            Stream reportStream = report.Render("Image", deviceInfo, urlAccessParameters, out mimeType, out extension);
            m_streams.Add(reportStream);
            urlAccessParameters.Remove("rs:PersistStreams");
            urlAccessParameters.Add("rs:GetNextStream", "True");
            while (reportStream.Length != 0)
            {
                reportStream =
                    report.Render("Image", deviceInfo, urlAccessParameters, out mimeType, out extension);
                m_streams.Add(reportStream);
            }

            m_streams.RemoveAt(m_streams.Count - 1);

            foreach (Stream stream in m_streams)
                stream.Position = 0;
        }
        */
        private void zapiszButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            List<ReportParameter> paramList = new List<ReportParameter>();
            paramList.Add(new ReportParameter("jezyk", jezykComboBox.SelectedItem.ToString(), true));
            this.reportViewer1.LocalReport.SetParameters(paramList);
            reportViewer1.RefreshReport();

            this.Cursor = Cursors.Default;

        }

        // drukowanie
        private int m_currentPageIndex;
        private IList<Stream> m_streams;

        private Stream CreateStream(string name,
          string fileNameExtension, Encoding encoding,
          string mimeType, bool willSeek)
        {
            Stream stream = new FileStream(name +
               "." + fileNameExtension, FileMode.Create);
            m_streams.Add(stream);
            return stream;
        }

        private void Export(LocalReport report)
        {
            string deviceInfo =
              "<DeviceInfo>" +
              "  <OutputFormat>EMF</OutputFormat>" +
              "  <PageWidth>21cm</PageWidth>" +
              "  <PageHeight>29.7cm</PageHeight>" +
              "  <MarginTop>1cm</MarginTop>" +
              "  <MarginLeft>1.4cm</MarginLeft>" +
              "  <MarginRight>1.4cm</MarginRight>" +
              "  <MarginBottom>0cm</MarginBottom>" +
              "</DeviceInfo>";
            Warning[] warnings;
            m_streams = new List<Stream>();
            report.Render("Image", deviceInfo, CreateStream,
               out warnings);
            foreach (Stream stream in m_streams)
                stream.Position = 0;
        }

        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new
               Metafile(m_streams[m_currentPageIndex]);
            ev.Graphics.DrawImage(pageImage, ev.PageBounds);            
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
        }

        private void Print(PrinterSettings printerSettings)
        {
            if (m_streams == null || m_streams.Count == 0)
                return;

            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings = printerSettings;
            printDoc.PrinterSettings.Duplex = Duplex.Vertical;
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            printDoc.Print();
        }

        private void Run()
        {
             PrintDialog printDialog = new PrintDialog();
             if (printDialog.ShowDialog() == DialogResult.OK)
             {
                 Export(reportViewer1.LocalReport);
                 m_currentPageIndex = 0;
                 Print(printDialog.PrinterSettings);
             }
           
        }

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

        public void HandlePrint(object sender, CancelEventArgs e)
        {
            Run();
            e.Cancel = true;
        }

    }
}