' 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.Xml
Imports System.Text
Imports System.IO

Public Class DP_Alerte

    Public Sub LECTURE_MSG(ByRef MsgRef As String)

        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        DP.Write_Trace_Tech(X_DP_ReqId, "LECTURE_MSG", MsgRef)

        Try



            Dim objRequest As System.Net.HttpWebRequest


            objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/lecture_msg/" & MsgRef)
            'objRequest = System.Net.HttpWebRequest.CreateHttp("http://127.0.0.1:13000")
            'RichTextBox1.AppendText(objRequest.RequestUri.ToString + Chr(10))
            objRequest.Method = "POST"
            objRequest.Timeout = 30000

            objRequest.ClientCertificates.Add(DP.DP_get_certif)

            objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            'objRequest.ContentType = "text/plain"


            objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            Dim objResponse As System.Net.HttpWebResponse = objRequest.GetResponse()
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())


            My.Computer.FileSystem.WriteAllText(Config.DP_Directory & "Msg\" & MsgRef, StreamReader.ReadToEnd.ToString, False)
            StreamReader.Close()

            Dim xmldoc As New XmlDocument
            'xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Msg\" & MsgRef)
            xmldoc.Load(Config.DP_Directory & "Msg\" & MsgRef)
            Me.DP_MsgTableAdapter.Insert(xmldoc.GetElementsByTagName("ref").Item(0).InnerText, xmldoc.GetElementsByTagName("type").Item(0).InnerText, _
                                         xmldoc.GetElementsByTagName("dateLecture").Item(0).InnerText, xmldoc.GetElementsByTagName("dateEmission").Item(0).InnerText, _
                                         xmldoc.GetElementsByTagName("dateExpiration").Item(0).InnerText, "", False, "", 0, Now, _
                                         xmldoc.GetElementsByTagName("emetteur").Item(0).InnerText, xmldoc.GetElementsByTagName("titre").Item(0).InnerText)
         

            DP_ALERTE_PRODUIT_insert(xmldoc)

            'If xmldoc.GetElementsByTagName("ref").Count > 0 Then
            'MsgRef = Mid(xmldoc.GetElementsByTagName("ref").Item(0).Value, InStrRev(xmldoc.GetElementsByTagName("ref").Item(0).Value, "/") + 1)
            'DP.Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", "MESSAGE:" & MsgRef)
            DP.Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", "MESSAGE:" & MsgRef)
            'Else
            '    MsgRef = ""
            '    DP.Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", "OK")
            'End If



        Catch wex As System.Net.WebException
            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()
                Dim xml_retour As New XmlDocument
                xml_retour.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")
                If XMLelementliste.Count > 0 Then
                    DP.Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                Else
                    DP.Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", wex.Message.ToString)
                End If
            Else
                DP.Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", wex.Message.ToString)
            End If


        End Try



    End Sub
    Public Sub AR_MSG(ByVal MsgRef As String)
        Dim DP_msg = Me.DP_MsgTableAdapter.GetDataBy_MsgRef(MsgRef).Item(0)

        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString



        Try
            Dim objRequest As System.Net.HttpWebRequest


            objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/ar_msg/" & MsgRef)
            If Val(DP_msg.AR_nbr_transmission) = 0 Then
                DP.Write_Trace_Tech(X_DP_ReqId, "AR_MSG", X_DP_ReqId)
            Else
                DP.Write_Trace_Tech("", "REQUETE_EN_ATTENTE_RENVOYEE", "AR " & MsgRef)
                objRequest.Headers.Add("X-DP-ASyncReq", "AR-MSG")
            End If
            'objRequest = System.Net.HttpWebRequest.CreateHttp("http://127.0.0.1:13000")
            objRequest.Method = "POST"
            objRequest.Timeout = 30000

            objRequest.ClientCertificates.Add(DP.DP_get_certif)

            objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            objRequest.ContentType = "application/x-www-form-urlencoded"


            objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            Dim postdata As String = Format(Now, "yyyy-MM-dd") & "T" & Format(Now, "HH:mm:ss") & ".000Z"

            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
            objRequest.ContentLength = byteArray.Length
            ' Get the request stream.
            Dim dataStream As Stream = objRequest.GetRequestStream
            ' Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length)
            ' Close the Stream object.
            dataStream.Close()


            Dim objResponse As System.Net.HttpWebResponse = objRequest.GetResponse()
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\" & X_DP_ReqId, StreamReader.ReadToEnd, True)

            StreamReader.Close()

            'If DP_msg.AR_sent = False Then
            '    AR_MSG(MsgRef_Label.Text)
            'End If

            Me.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, "OK", DP_msg.AR_nbr_transmission + 1, Now, MsgRef)

            DP.Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", "OK")

        Catch wex As System.Net.WebException
            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()
                Dim xml_retour As New XmlDocument
                xml_retour.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")
                If XMLelementliste.Count > 0 Then
                    DP.Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Dim next_trans_time As Date = Now
                    Dim Generator As System.Random = New System.Random()
                    next_trans_time = next_trans_time.AddMinutes(45 + Generator.Next(0, 30))
                    Me.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, XMLelementliste.Item(0).Item("code").GetAttribute("code"), DP_msg.AR_nbr_transmission + 1, next_trans_time, MsgRef)
                    If DP_msg.AR_nbr_transmission + 1 < 2 Then
                        DP.Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
                    End If
                Else
                    DP.Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", wex.Message.ToString)
                    Dim next_trans_time As Date = Now
                    Dim Generator As System.Random = New System.Random()
                    next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
                    Me.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, wex.Message, DP_msg.AR_nbr_transmission, next_trans_time, MsgRef)
                    If DP_msg.AR_nbr_transmission < 2 Then
                        DP.Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
                    End If
                End If
            Else
                DP.Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", wex.Message.ToString)
                Dim next_trans_time As Date = Now
                Dim Generator As System.Random = New System.Random()
                next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
                Me.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, wex.Message, DP_msg.AR_nbr_transmission, next_trans_time, MsgRef)
                If DP_msg.AR_nbr_transmission < 2 Then
                    DP.Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
                End If
            End If
        Catch ex As Exception

        End Try

    End Sub
    Public Sub affichage_Msg(ByVal MsgRef As String)
        Dim xmldoc As New XmlDocument
        xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Msg\" & MsgRef)
        RichTextBox1.Text = ""
        MsgRef_Label.Text = xmldoc.GetElementsByTagName("ref").Item(0).InnerText
        Select Case xmldoc.GetElementsByTagName("type").Item(0).InnerText
            Case "ALERTE_SANITAIRE"
                MsgTyp_Label.Text = "URGENCE" + vbCrLf + "Alerte sanitaire"
                Info_Label.Text = "INFORMATION URGENTE A PRENDRE EN COMPTE"
            Case "ALERTE_PRODUIT", "RETOUR_PRODUIT"
                If UCase(xmldoc.GetElementsByTagName("demandeRetour").Item(0).InnerText) = "NON" Then
                    MsgTyp_Label.Text = "Alerte"
                Else
                    MsgTyp_Label.Text = "Rappel/Retrait"
                End If
                If UCase(Mid(MsgRef, 1, 3)) = "MED" Then
                    MsgTyp_Label.Text = MsgTyp_Label.Text + vbCrLf + "MEDICAMENT"
                Else
                    MsgTyp_Label.Text = MsgTyp_Label.Text + vbCrLf + "PRODUIT"
                End If
                Pied_Page_Label.Text = "Le laboratoire, seul responsable des informations portées sur ce bordereau, a mandaté le CNOP pour les router aux Pharmaciens." + vbCrLf + _
"La responsabilité du CNOP n’est pas engagée au-delà de ce mandat."
                Info_Label.Text = "INFORMATION URGENTE A TRAITER SANS DELAI ET ARCHIVER"

            Case "INFORMATION"
                MsgTyp_Label.Text = "Information"
                Info_Label.Text = "MESSAGE D’INFORMATION"
        End Select

        MsgDate_Label.Text = "Date: " & xmldoc.GetElementsByTagName("dateEmission").Item(0).InnerText
        MsgEme_Label.Text = "emetteur: " & xmldoc.GetElementsByTagName("emetteur").Item(0).InnerText
        MsgTit_Label.Text = "objet: " & xmldoc.GetElementsByTagName("titre").Item(0).InnerText
        RichTextBox1.Text = RichTextBox1.Text & (xmldoc.GetElementsByTagName("texte").Item(0).InnerText & vbCrLf & vbCrLf)

        If xmldoc.GetElementsByTagName("laboratoire").Count > 0 Then
            RichTextBox1.Text = RichTextBox1.Text & ("________________________________________________________________________________________" & vbCrLf & "LABORATOIRE:" & vbCrLf)
            For Each item_ As XmlNode In xmldoc.GetElementsByTagName("laboratoire").Item(0).ChildNodes
                RichTextBox1.Text = RichTextBox1.Text & (item_.Name & ": " & item_.InnerText & vbCrLf)
            Next
        End If

        If xmldoc.GetElementsByTagName("produits").Count > 0 Then
            RichTextBox1.Text = RichTextBox1.Text & ("________________________________________________________________________________________" & vbCrLf & "PRODUITS:" & vbCrLf)
            For Each produit As XmlElement In xmldoc.GetElementsByTagName("produits").Item(0).ChildNodes
                RichTextBox1.Text = RichTextBox1.Text & (vbCrLf & "CIP: " & produit.GetElementsByTagName("code").Item(0).InnerText & vbCrLf)
                RichTextBox1.Text = RichTextBox1.Text & (produit.GetElementsByTagName("libelle").Item(0).InnerText & vbCrLf)


                If produit.GetElementsByTagName("lots").Item(0).Attributes.Count > 0 Then
                    RichTextBox1.Text = RichTextBox1.Text & ("lots ensemble: " & produit.GetElementsByTagName("lots").Item(0).Attributes.GetNamedItem("ensemble").Value & vbCrLf)

                    If produit.GetElementsByTagName("lots").Item(0).ChildNodes.Count > 0 Then
                        For Each lot As XmlElement In produit.GetElementsByTagName("lots").Item(0).ChildNodes
                            RichTextBox1.Text = RichTextBox1.Text & ("num: " & lot.GetAttribute("num") & "  per: " & lot.GetAttribute("per") & vbCrLf)
                        Next
                    End If

                End If
                'richTextBox1.Text = richTextBox1.Text & (vbCrLf)
            Next
        End If

        If xmldoc.GetElementsByTagName("type").Item(0).InnerText = "ALERTE_PRODUIT" Or xmldoc.GetElementsByTagName("type").Item(0).InnerText = "RETOUR_PRODUIT" Then
            RichTextBox1.Text = RichTextBox1.Text & vbCrLf & "Destinataire:" & vbCrLf & vbCrLf & "Adresse:" & vbCrLf & vbCrLf
            RichTextBox1.Text = RichTextBox1.Text & "Traité le:                Par:                     Cachet de la pharmacie " & vbCrLf & "Action menée:" & vbCrLf & vbCrLf & vbCrLf & "Signature:"
        End If


    End Sub






    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.DP_ALERTE_PRODUITTableAdapter.Update_Vue_By_MsgRef(True, MsgRef_Label.Text)

        If Me.DP_MsgTableAdapter.GetDataBy_MsgRef(MsgRef_Label.Text).Rows.Count > 0 Then

            Dim DP_msg = Me.DP_MsgTableAdapter.GetDataBy_MsgRef(MsgRef_Label.Text).Item(0)

            Dim new_reader As String = DP_msg.Reader
            If InStr(new_reader, "/" & current_User.ID & "/") = 0 Then
                new_reader = new_reader & "/" & current_User.ID & "/"
            End If
            'If DP_msg.AR_sent = False Then
            '    AR_MSG(MsgRef_Label.Text)
            'End If

            Me.DP_MsgTableAdapter.Update_by_MsgRef(new_reader, DP_msg.AR_sent, DP_msg.AR_Statut, DP_msg.AR_nbr_transmission, DP_msg.AR_next_trans_time, MsgRef_Label.Text)

        End If
        Me.Close()

    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
       

        Dim b As New Bitmap(Panel1.Width, Panel1.Height)
        Panel1.DrawToBitmap(b, Panel1.ClientRectangle)
        Dim destRect As New Rectangle(Panel1.Location.X, Panel1.Location.Y, e.MarginBounds.Width, e.MarginBounds.Height) ' Panel1.Width, Panel1.Height)
        e.Graphics.DrawImage(b, destRect)




    End Sub

    Private Sub Print_Button_Click(sender As Object, e As EventArgs) Handles Print_Button.Click
        Dim pf As New Microsoft.VisualBasic.PowerPacks.Printing.PrintForm

        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
             Bandeau_info_bas_show("Impression de l’alerte en cours…")

            PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings

            Dim tampon = RichTextBox1.Text

            RichTextBox1.Visible = False
            Text_Label.Text = ""
            Text_Label.Visible = True

debut:
            Text_Label.Text = Mid(RichTextBox1.Text, 1, RichTextBox1.GetCharIndexFromPosition(New Point(RichTextBox1.Location.X + RichTextBox1.Width, RichTextBox1.Location.Y + RichTextBox1.Height - 200)))
            If RichTextBox1.TextLength > RichTextBox1.GetCharIndexFromPosition(New Point(RichTextBox1.Location.X + RichTextBox1.Width, RichTextBox1.Location.Y + RichTextBox1.Height - 200)) Then
                RichTextBox1.Text = Mid(RichTextBox1.Text, RichTextBox1.GetCharIndexFromPosition(New Point(RichTextBox1.Location.X + RichTextBox1.Width, RichTextBox1.Location.Y + RichTextBox1.Height - 200)) + 1)
            Else
                RichTextBox1.Text = ""
            End If

            PrintDocument1.Print()

            If RichTextBox1.Text.Length > 1 Then
                GoTo debut
            End If

            RichTextBox1.Text = tampon
            RichTextBox1.Visible = True
            Text_Label.Text = ""
            Text_Label.Visible = False

Bandeau_info_bas_hide()'Bandeau_info_bas_show_thread)

        End If
    End Sub

    Public Sub DP_ALERTE_PRODUIT_insert(ByVal Msg As XmlDocument)

        If Msg.GetElementsByTagName("type").Item(0).InnerText <> "ALERTE_PRODUIT" Then
            Exit Sub
        End If

        If Msg.GetElementsByTagName("produits").Count > 0 Then
            For Each produit As XmlElement In Msg.GetElementsByTagName("produits").Item(0).ChildNodes
                If produit.GetElementsByTagName("lots").Count > 0 Then
                    If Not produit.GetElementsByTagName("lots").Item(0).Attributes.GetNamedItem("ensemble") Is Nothing Then
                        If produit.GetElementsByTagName("lots").Item(0).Attributes.GetNamedItem("ensemble").Value = "LISTE" Then
                            For Each lot As XmlElement In produit.GetElementsByTagName("lots").Item(0).ChildNodes
                                If Me.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, lot.GetAttribute("num")).Rows.Count = 0 Then
                                    Me.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, lot.GetAttribute("num"), False)
                                End If
                            Next
                        Else
                            If Me.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*").Rows.Count = 0 Then
                                Me.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*", False)
                            End If
                        End If
                    Else
                        If Me.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*").Rows.Count = 0 Then
                            Me.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*", False)
                        End If
                    End If
                Else
                    If Me.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*").Rows.Count = 0 Then
                        Me.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*", False)
                    End If
                End If
            Next
        End If
    End Sub

    Private Sub RichTextBox1_LinkClicked(sender As Object, e As LinkClickedEventArgs) Handles RichTextBox1.LinkClicked
        System.Diagnostics.Process.Start("explorer.exe", e.LinkText)
    End Sub

    

End Class