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.Reflection;
using System.IO;


namespace Baza_Reklam
{
    public partial class FactureViewer : Form
    {
        private int idFaktury;
        private int idKorekty;
        private int idPoprzedniejKorekty;

        /// <summary>
        /// true - faktura, false - proforma
        /// </summary>
        bool rodzaj;
        DataSet ds;

        public FactureViewer(int idFakt,bool rodzaj, int old)
        {
            InitializeComponent();
            
            idFaktury = idFakt;

            this.rodzaj = rodzaj;

            this.zapiszButton.Click += new EventHandler(zapiszButton_Click);

            fakturaTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
            fakturA_DETAILSTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            proformaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            ds = new DataSet();

            //zczytuje dane z pliku z tlumaczeniami
            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Baza_Reklam.Raporty.faktura.xml");
            ds.ReadXml(s);

            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idFakt);

            //ustawienie parametrów, nowych datasoure dla raportu
            
            //ustawianie danych dla raportu
            if (this.rodzaj)
            {
                typComboBox.Enabled = false;               
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFakt)));
            
            }
            else {
                jezykComboBox.Enabled = false;
                reportViewer1.LocalReport.ReportEmbeddedResource = "Baza_Reklam.Raporty.proformaReversed.rdlc";
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", proformaTableAdapter.GetDataByIdFaktury(idFakt)));
            }            
            
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails", fakturA_DETAILSTableAdapter1.GetDataByIdFaktury(idFakt)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            List<ReportParameter> paramList = new List<ReportParameter>();

            //Produkcja ma domyślnie bez podpisu 

            if (User.getUser().St_produkcja)
            {
                podpisCheckBox.CheckState = CheckState.Unchecked;
                paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
                this.reportViewer1.LocalReport.SetParameters(paramList);
            }

            //nadpisanie drukowania
            //this.reportViewer1.Print += new CancelEventHandler(HandlePrint);
            /*
            if (rodzaj)
            {
                this.reportViewer1.Print += new CancelEventHandler(HandlePrint);
            }
            */

            jezykComboBox.SelectedIndex = 0;
            typComboBox.SelectedIndex = 1;

        }

    /// <param name="rodzaj">true = proforma</param>
    public FactureViewer(int idFakt, bool r)
        {
            InitializeComponent();
    
            reportViewer1.LocalReport.ReportEmbeddedResource = "Baza_Reklam.Raporty.fakturaReversed2.rdlc";
            idFaktury = idFakt;
            this.rodzaj = r;

            this.zapiszButton.Click += zapiszButton2_Click;

            fakturaTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURA_DETAILS2TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            proformaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            ds = new DataSet();

            //zczytuje dane z pliku z tlumaczeniami
            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Baza_Reklam.Raporty.faktura.xml");
            ds.ReadXml(s);

            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idFakt);

            //ustawienie parametrów, nowych datasoure dla raportu

            //ustawianie danych dla raportu
            typComboBox.Enabled = false;
            
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFakt)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails2", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idFakt)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            List<ReportParameter> paramList = new List<ReportParameter>();

            //Produkcja ma domyślnie bez podpisu 
            if (User.getUser().St_produkcja)
            {
                podpisCheckBox.CheckState = CheckState.Unchecked;
            }
            
            paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
            
            if (this.rodzaj)
            {
                paramList.Add(new ReportParameter("proforma", "True", true));
            }
            else
            {
                paramList.Add(new ReportParameter("proforma", "False", true));
            }

            paramList.Add(new ReportParameter("zaplacono", zaplaconoCheckBox.Checked.ToString(), true));
           
            this.reportViewer1.LocalReport.SetParameters(paramList);
          
            jezykComboBox.SelectedIndex = 0;
            typComboBox.SelectedIndex = 1;
        }

        /// <summary>
        /// Przy pierwszej korekcie  idKorygowanejFaktury = idPoprzedniejKorekty
        /// </summary>
        public FactureViewer(int idKorekty, int idKorygowanejFaktury, int idPoprzedniejKorekty)
        {
            InitializeComponent();

            powodKorektyComboBox.Enabled = true;
            opisTextBox.ReadOnly = !User.getUser().St_kierownik;
            opisTextBox.BackColor = User.getUser().St_kierownik ? Color.White : Color.WhiteSmoke;

            reportViewer1.LocalReport.ReportEmbeddedResource = "Baza_Reklam.Raporty.fakturaKorekta.rdlc";

            this.idFaktury = idKorygowanejFaktury;
            this.idKorekty = idKorekty;
            this.idPoprzedniejKorekty = idPoprzedniejKorekty;

            this.zapiszButton.Click += zapiszKorektaButton_Click;
                        
            fakturaTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURA_DETAILS2TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            proformaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            ds = new DataSet();

            //zczytuje dane z pliku z tlumaczeniami
            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Baza_Reklam.Raporty.faktura.xml");
            ds.ReadXml(s);

            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idKorekty);

            //ustawienie parametrów, nowych datasoure dla raportu

            typComboBox.Enabled = false;
           
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Korekta",fakturaTableAdapter1.GetDataByIdFaktury(idKorekty)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFaktury)));
     
            //piersza korekta
            if (idPoprzedniejKorekty == idFaktury)
            {
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails2", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idFaktury)));
            }
            else
            {
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails2", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idPoprzedniejKorekty)));
            }
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetailsKorekty", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idKorekty)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            List<ReportParameter> paramList = new List<ReportParameter>();

            //Produkcja ma domyślnie bez podpisu 

            if (User.getUser().St_produkcja)
            {
                podpisCheckBox.CheckState = CheckState.Unchecked;
                paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
                this.reportViewer1.LocalReport.SetParameters(paramList);
            }
            jezykComboBox.SelectedIndex = 0;
            typComboBox.SelectedIndex = 1;

        }

        /*
        /// <summary>
        ///  FAKTURA DLA POZNANIA
        /// </summary>
        /// <param name="idFakt"></param>
        public FactureViewer(int idFakt)
        {
            InitializeComponent();

            idFaktury = idFakt;

            this.zapiszButton.Click += new EventHandler(zapiszPoznanButton_Click);

            fakturaTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
            fakturA_DETAILSTableAdapter1.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            proformaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            ds = new DataSet();

            //zczytuje dane z pliku z tlumaczeniami
            Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("Baza_Reklam.Raporty.faktura.xml");
            ds.ReadXml(s);

            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idFakt);

            typComboBox.Enabled = false;
          //  wersjaComboBox.Enabled = false;
         // jezykComboBox.Enabled = false;

            reportViewer1.LocalReport.ReportEmbeddedResource = "Baza_Reklam.Raporty.fakturaPoznan.rdlc";
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFakt)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails", fakturA_DETAILSTableAdapter1.GetDataByIdFaktury(idFakt)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            jezykComboBox.SelectedIndex = 0;
            typComboBox.SelectedIndex = 1;
        //    wersjaComboBox.SelectedIndex = 0;
        }
        */


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

            nUMERTextBox.Enabled = User.getUser().St_kierownik;
        }

        private void zapiszButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            //zapisanie zmian w polu "opis" faktury
            fAKTURYBindingSource.EndEdit();
            fAKTURYTableAdapter.Update(this.rEKLAMADataSet.FAKTURY);
            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idFaktury);

            reportViewer1.Reset();
            reportViewer1.LocalReport.ReportEmbeddedResource = this.rodzaj ? "Baza_Reklam.Raporty.fakturaReversed.rdlc" : "Baza_Reklam.Raporty.proformaReversed.rdlc";
           
            //ustawienie parametrów, nowych datasoure dla raportu
            List<ReportParameter> paramList = new List<ReportParameter>();

            if (this.rodzaj)
            {               
                paramList.Add(new ReportParameter("jezyk", jezykComboBox.SelectedItem.ToString(), true));
                paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
                this.reportViewer1.LocalReport.SetParameters(paramList);
                reportViewer1.LocalReport.DataSources.Clear();
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFaktury)));
           
            }
            else
            {
                paramList.Add(new ReportParameter("typ", typComboBox.SelectedItem.ToString(), true));
                paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
                this.reportViewer1.LocalReport.SetParameters(paramList);
                reportViewer1.LocalReport.DataSources.Clear();
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", proformaTableAdapter.GetDataByIdFaktury(idFaktury)));
            }     

            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails", fakturA_DETAILSTableAdapter1.GetDataByIdFaktury(idFaktury)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            reportViewer1.RefreshReport();
            //MessageBox.Show(reportViewer1.LocalReport.ReportEmbeddedResource);
            this.Cursor = Cursors.Default;

        }

        /// <summary>
        /// WERSJA DLA POZNANIA
        /// </summary>
        private void zapiszPoznanButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            //zapisanie zmian w polu "opis" faktury
            fAKTURYBindingSource.EndEdit();
            fAKTURYTableAdapter.Update(this.rEKLAMADataSet.FAKTURY);
            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY,idKorekty);

            //ustawienie parametrów, nowych datasoure dla raportu
            List<ReportParameter> paramList = new List<ReportParameter>();

            paramList.Add(new ReportParameter("jezyk", jezykComboBox.SelectedItem.ToString(), true));
            paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
            this.reportViewer1.LocalReport.SetParameters(paramList);
            reportViewer1.LocalReport.DataSources.Clear();
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFaktury)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Korekta", fakturaTableAdapter1.GetDataByIdFaktury(idKorekty)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails", fakturA_DETAILSTableAdapter1.GetDataByIdFaktury(idFaktury)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            reportViewer1.RefreshReport();
            //MessageBox.Show(reportViewer1.LocalReport.ReportEmbeddedResource);
            this.Cursor = Cursors.Default;

        }

        private void zapiszKorektaButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            //zapisanie zmian w polu "opis" faktury
            fAKTURYBindingSource.EndEdit();
            fAKTURYTableAdapter.Update(this.rEKLAMADataSet.FAKTURY);
            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idKorekty);

            reportViewer1.LocalReport.DataSources.Clear();

            //ustawienie parametrów, nowych datasoure dla raportu
            List<ReportParameter> paramList = new List<ReportParameter>();
            paramList.Add(new ReportParameter("jezyk", jezykComboBox.SelectedItem.ToString(), true));
            paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));

            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Korekta",fakturaTableAdapter1.GetDataByIdFaktury(idKorekty)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFaktury)));
     
            //piersza korekta
            if (idPoprzedniejKorekty == idFaktury)
            {
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails2", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idFaktury)));
            }
            else
            {
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails2", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idPoprzedniejKorekty)));
            }
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetailsKorekty", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idKorekty)));
           
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));
            this.reportViewer1.LocalReport.SetParameters(paramList);

            reportViewer1.RefreshReport();
            //MessageBox.Show(reportViewer1.LocalReport.ReportEmbeddedResource);
            this.Cursor = Cursors.Default;

        }

        private void zapiszButton2_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            //zapisanie zmian w polu "opis" faktury
            fAKTURYBindingSource.EndEdit();
            fAKTURYTableAdapter.Update(this.rEKLAMADataSet.FAKTURY);
            fAKTURYTableAdapter.FillByIdFaktury(this.rEKLAMADataSet.FAKTURY, idFaktury);

            //ustawienie parametrów, nowych datasoure dla raportu
            List<ReportParameter> paramList = new List<ReportParameter>();

            paramList.Add(new ReportParameter("jezyk", jezykComboBox.SelectedItem.ToString(), true));
            paramList.Add(new ReportParameter("podpis", podpisCheckBox.Checked.ToString(), true));

            if (this.rodzaj)
            {
                paramList.Add(new ReportParameter("proforma", "True", true));
            }
            else
            {
                paramList.Add(new ReportParameter("proforma", "False", true));
            }
            paramList.Add(new ReportParameter("zaplacono", zaplaconoCheckBox.Checked.ToString(), true));
        
            this.reportViewer1.LocalReport.SetParameters(paramList);
            reportViewer1.LocalReport.DataSources.Clear();
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Faktura", fakturaTableAdapter1.GetDataByIdFaktury(idFaktury)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("FakturaDetails2", fAKTURA_DETAILS2TableAdapter.GetDataIdFaktury(idFaktury)));
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("tlumaczenia", ds.Tables[0]));

            reportViewer1.RefreshReport();
            //MessageBox.Show(reportViewer1.LocalReport.ReportEmbeddedResource);
            this.Cursor = Cursors.Default;

        }

       //drukowanie raportu serwerowego
        /*
        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)
        {
            MessageBox.Show("PrintBegin");
            if (m_streams == null || m_streams.Count == 0)
                return;

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

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

        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            MessageBox.Show("PrintPage1");
            Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);
            pageImage.Save("C:\\testestPRO.emf");

            // 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.

            MessageBox.Show("PrintPage2nnn");
            RectangleF adjustedRect = new RectangleF(
                ev.PageBounds.Left - ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - ev.PageSettings.HardMarginY,
                ev.PageBounds.Width, ev.PageBounds.Height);
            MessageBox.Show(adjustedRect.Top.ToString() + "*" + adjustedRect.Height.ToString() + "*" + adjustedRect.Width.ToString());
            ev.Graphics.DrawImage(pageImage, adjustedRect);
            MessageBox.Show("PrintPage4");
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
            MessageBox.Show("PrintPage5");
        }

        private void Export(ServerReport report)
        {
            MessageBox.Show("ExportBegin");

            string deviceInfo =

              "<DeviceInfo>" +

              "  <OutputFormat>EMF</OutputFormat>" +

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

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

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

              "  <MarginLeft>1cm</MarginLeft>" +

              "  <MarginRight>1cm</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;

            MessageBox.Show("ExportEnd");
        }
        */

        // drukowanie raportu lokalnego
        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>19cm</PageWidth>" +
              "  <PageHeight>25cm</PageHeight>" +
              "  <MarginTop>1cm</MarginTop>" +
              "  <MarginLeft>1cm</MarginLeft>" +
              "  <MarginRight>1cm</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);
                Dispose();
            }

        }

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

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

        private void powodKorektyComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataRowView row = (DataRowView)fAKTURYBindingSource.Current;
            row["opis"] = powodKorektyComboBox.SelectedItem.ToString();
            fAKTURYBindingSource.EndEdit();
            
            opisTextBox.Text = powodKorektyComboBox.SelectedItem.ToString();
        }

   }
}