' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Xml

Public Class Ordonnancier

    Private drawString As String
    Private mStringPos As Integer

    Private Sub affiche_ordonnancier() Handles STUP_RadioButton.Click, Liste1_Liste2_RadioButton.Click, Début_DateTimePicker.ValueChanged, Fin_DateTimePicker.ValueChanged
        Début_DateTimePicker.Value = New DateTime(Début_DateTimePicker.Value.Year, Début_DateTimePicker.Value.Month, Début_DateTimePicker.Value.Day, 0, 0, 1)
        Fin_DateTimePicker.Value = New DateTime(Fin_DateTimePicker.Value.Year, Fin_DateTimePicker.Value.Month, Fin_DateTimePicker.Value.Day, 23, 59, 59)
        Dim MyDatatable As New DataTable

        If STUP_RadioButton.Checked = True Then
            MyDatatable = Me.Ordonnancier_StupéfiantsTableAdapter1.GetDataBy_Date(Début_DateTimePicker.Value, Fin_DateTimePicker.Value)

        ElseIf Liste1_Liste2_RadioButton.Checked = True Then
            MyDatatable = Me.Ordonnancier_ListeI_ListeIITableAdapter1.GetDataBy_Date(Début_DateTimePicker.Value, Fin_DateTimePicker.Value)
        End If
        DataGridView1.DataSource = MyDatatable
        For c = 0 To DataGridView1.ColumnCount - 1
            DataGridView1.Columns(c).HeaderText = Replace(DataGridView1.Columns(c).HeaderText, "_", " ")
        Next
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        'Dim drawFont As New Font("Lucida console", 8)
        'Dim drawBrush As New SolidBrush(Color.Black)
        ''e.HasMorePages = True
        ''e.Graphics.DrawString(drawString, drawFont, drawBrush, 0, 0)



        '--- Setup graphics context 
        Dim fnt As New Font("Lucida console", 10)
        e.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias

        '--- Calculate the number of characters that fit inside the margins 
        Dim area As SizeF = New SizeF(e.MarginBounds.Width, e.MarginBounds.Height)
        Dim lines, chars As Integer
        e.Graphics.MeasureString(drawString.Substring(mStringPos), fnt, area, StringFormat.GenericTypographic, chars, lines)
        '--- Print the amount of text that fits inside the margins 
        Dim rc As New RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height)
        e.Graphics.DrawString(drawString.Substring(mStringPos, chars), fnt, _
          Brushes.Black, rc, StringFormat.GenericTypographic)
        '--- Advance print position by <chars> 
        mStringPos += chars
        '--- We'll need another page if not all characters got printed 
        e.HasMorePages = mStringPos < drawString.Length
        '--- Cleanup 
        fnt.Dispose()

    End Sub

    Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
        '--- Start printing at the start of the string 
        mStringPos = 0
    End Sub

    Private Sub Print_Button_Click(sender As Object, e As EventArgs) Handles Print_Button.Click
        drawString = ""

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load(Application.StartupPath + "\InfoPro.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("ORDONNANCIER")
        drawString = XMLelementliste.Item(0).Item("EnTete").InnerText + Chr(10) + "ORDONNANCIER édité le " + Now.ToString + _
            " période du " + Début_DateTimePicker.Value.ToShortDateString + " au " + Fin_DateTimePicker.Value.ToShortDateString + Chr(10) + "________________________________________________________________________________________________" + Chr(10)

        For r = 0 To DataGridView1.Rows.Count - 2
            For c = 0 To DataGridView1.ColumnCount - 2
                Select Case c
                    Case 1
                        drawString = drawString + Chr(10) + "Prescripteur: "
                    Case 4
                        drawString = drawString + Chr(10) + "Bénéficiaire: "
                    Case 7
                        drawString = drawString + Chr(10)
                    Case 8
                        drawString = drawString + " Quantité: "
                    Case Else
                        drawString = drawString + Chr(10)
                End Select
                drawString = drawString + DataGridView1.Item(c, r).Value.ToString + " "
            Next
            If Replace(DataGridView1.Item(DataGridView1.ColumnCount - 1, r).Value.ToString, " ", "") <> "" Then
                drawString = drawString + Chr(10) + "Porteur de l'ordonnance: " + DataGridView1.Item(DataGridView1.ColumnCount - 1, r).Value.ToString
            End If
            drawString = drawString + Chr(10) + "________________________________________________________________________________________________" + Chr(10)
        Next

        PrintDocument1.DefaultPageSettings.Margins = New Margins(10, 10, 10, 10)
        PrintPreviewDialog1.Document = PrintDocument1
        PrintDialog1.Document = PrintDocument1
        If PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PrintPreviewDialog1.ShowDialog()
            If PrintPreviewDialog1.DialogResult = DialogResult.OK Then
                PrintDocument1.Print()
            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim WebBrowser1 As New WebBrowser
        Dim ConfigXml As New XmlDocument
        ConfigXml.Load(Application.StartupPath + "\InfoPro.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("ORDONNANCIER")
        WebBrowser1.DocumentText = "ORDONNANCIER édité le " + Now.ToString + "<br>" + XMLelementliste.Item(0).Item("EnTete").InnerText + "<br>" + _
            " période du " + Début_DateTimePicker.Value.ToShortDateString + " au " + Fin_DateTimePicker.Value.ToShortDateString + "<br>" + "<br>"

        Do While WebBrowser1.ReadyState = WebBrowserReadyState.Loading
            Application.DoEvents()
        Loop
        If (Not (WebBrowser1.Document Is Nothing)) Then

            With WebBrowser1.Document
         
    
                Dim TableElem As HtmlElement = .CreateElement("TABLE")
                TableElem.SetAttribute("border", "1")
                TableElem.SetAttribute("cellspacing", "0")

                .Body.AppendChild(TableElem)

                Dim TableRow As HtmlElement

                ' Create the table header. 
                Dim TableHeader As HtmlElement = .CreateElement("THEAD")
                TableElem.AppendChild(TableHeader)
                TableRow = .CreateElement("TR")
                TableHeader.AppendChild(TableRow)

                Dim HeaderElem As HtmlElement
                Dim liste_colonne As New List(Of String)
                liste_colonne.Add("Date") '0
                liste_colonne.Add("Num") '1
                liste_colonne.Add("Prescripteur") '2
                liste_colonne.Add("Patient") '3
                liste_colonne.Add("Produit") '4
                liste_colonne.Add("Qté") '5
                For Each Col In liste_colonne
                    HeaderElem = .CreateElement("TH")
                    HeaderElem.InnerText = Col

                    TableRow.AppendChild(HeaderElem)
                Next

                ' Create table rows.
                Dim TableBody As HtmlElement = .CreateElement("TBODY")
                TableElem.AppendChild(TableBody)
                For Each Row As DataGridViewRow In DataGridView1.Rows
                    TableRow = .CreateElement("TR")
                    TableBody.AppendChild(TableRow)
                    For numcol = 0 To 5
                        Dim TableCell As HtmlElement = .CreateElement("TD")
                        'TableCell.SetAttribute("border", "1")
                        TableCell.SetAttribute("align", "center")
                        Select Case numcol
                            Case 0 'Date
                                TableCell.InnerText = DataGridView1.Item(6, Row.Index).Value
                            Case 1 'Num
                                TableCell.InnerText = DataGridView1.Item(0, Row.Index).Value
                            Case 2 'Prescripteur
                                TableCell.InnerText = DataGridView1.Item(1, Row.Index).Value & ", " & DataGridView1.Item(3, Row.Index).Value & ", " & DataGridView1.Item(2, Row.Index).Value & ", " & DataGridView1.Item(10, Row.Index).Value
                            Case 3 'Patient
                                TableCell.InnerText = DataGridView1.Item(4, Row.Index).Value & vbCrLf
                            Case 4 'Produit
                                TableCell.InnerText = DataGridView1.Item(7, Row.Index).Value & vbCrLf
                            Case 5 'Qté
                                TableCell.InnerText = DataGridView1.Item(8, Row.Index).Value & vbCrLf

                        End Select
                        TableRow.AppendChild(TableCell)

                    Next


                Next

            End With
        End If
        My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\ordonnancier_temp.html", WebBrowser1.Document.All(0).OuterHtml, False)

        Process.Start(Application.StartupPath + "\ordonnancier_temp.html")
        Threading.Thread.Sleep(1000)
        My.Computer.FileSystem.DeleteFile(Application.StartupPath + "\ordonnancier_temp.html")

    End Sub
End Class