Public Class Form1
    Public camera As Integer
    Public disque As Integer
    Private g As Date 'La date choisi par l'user
    Private h As Date 'La date choisi par l'user
    Private j As Long 'La date choisi par l'user
    Private k As Long 'La date choisi par l'user
    Private l As Long = 0 'La date choisi par l'user
    Private m As Long 'La date choisi par l'user
    Private p As Long 'La date choisi par l'user
    Private q As String 'La date choisi par l'user
    Dim Retour As Integer

    Dim a As Long
    Dim aa As Date
    Dim bb As Date

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Label1.Text = ""
        Me.Label2.Text = ""
        Me.Label9.Text = ""
        Me.Label10.Text = ""
        Me.GroupBox6.Hide()
        'Groupbox de test
        'Me.Label11.Text = ""
        'Me.Label12.Text = ""
        'Me.Label13.Text = ""
        'Me.Label14.Text = ""
        'Me.GroupBox3.Visible = True
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Label1.Text = Now.Date
        Me.Label2.Text = Now.ToLongTimeString
        Me.Label9.Text = (720 - l) & "/720min"
        Me.Label10.Text = ((Me.NumericUpDown4.Value - Me.NumericUpDown1.Value) * 60 + (Me.NumericUpDown3.Value - Me.NumericUpDown2.Value)) & "Min"

    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim d As New Date 'date choisi dans DateTimePicker
        Dim f As New Date 'date choisi dans DateTimePicker
        d = Me.DateTimePicker1.Value
        g = New Date(d.Year, d.Month, d.Day, Me.NumericUpDown1.Value, Me.NumericUpDown2.Value, Now.Second)
        If g <= Now Then
            MessageBox.Show("Date ou heure invalide", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Exit Sub
        End If
        Me.GroupBox3.Visible = True
        Timer2.Start()
        f = Me.DateTimePicker2.Value
        h = New Date(f.Year, f.Month, f.Day, Me.NumericUpDown4.Value, Me.NumericUpDown3.Value, Now.Second)
        If (h <= Now) Then
            MessageBox.Show("Date ou heure invalide", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Exit Sub
        End If
        Dim item1 As New ListViewItem
        Dim item2 As New ListViewItem

        p = DateDiff(DateInterval.Hour, g, h)
        j = DateDiff(DateInterval.Minute, g, h) ' - (p * 60) 'attention pour la récup' des données
        'q = p & " h" & j & " min"
        k = DateDiff(DateInterval.DayOfYear, g, h)
        'l = j + l



        If (l > 720) Then
            MessageBox.Show("Temps d'enregistrement maximal dépassé", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            l = l - j
            Exit Sub
        End If

        If (k < 0) Then
            MessageBox.Show("Date ou heure invalide fin avant début", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Exit Sub

        ElseIf (j < 0) Then
            MessageBox.Show("Date ou heure invalide fin avant début", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Exit Sub
        End If

        Dim b As Date
        Dim c As Long
        Dim bb As Date
        Dim cc As Long
        Dim cc1 As Long
        Dim old As Date
        Dim old2 As Date
        'Dim b1 As Date
        Dim c1 As Long
        'Dim c2 As Long
        For i As Integer = ListView1.Items.Count - 1 To 0 Step -1
            old = ListView1.Items(i).SubItems(1).Text
            'old2 = ListView1.Items(i).SubItems(2).Text
            b = ListView1.Items(i).Text
            c = DateDiff(DateInterval.Minute, g, b)
            bb = ListView1.Items(i).SubItems(1).Text
            cc = DateDiff(DateInterval.Minute, h, bb)

            If (c = 0 Or cc = 0) Then
                'g = ListView1.Items(i).Text 'Or h = ListView1.Items(i).SubItems(1).Text) Then
                MessageBox.Show("Date de début ou de fin déjà programmée", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                Exit Sub
            End If
        Next
        For i As Integer = ListView1.Items.Count - 1 To 0 Step -1
            For s As Integer = ListView1.Items.Count - 1 To 0 Step -1


                old = ListView1.Items(s).SubItems(1).Text
                old2 = ListView1.Items(i).Text

                b = ListView1.Items(i).Text

                c = DateDiff(DateInterval.Minute, old, g)
                c1 = DateDiff(DateInterval.Hour, old, g)

                cc = DateDiff(DateInterval.Minute, g, old2)
                cc1 = DateDiff(DateInterval.Hour, g, old2)

                'Groupbox de test
                'Me.Label11.Text = c & "mn"
                'Me.Label12.Text = c1 & "h"
                'Me.Label13.Text = cc & "mn"
                'Me.Label14.Text = cc1 & "h"

                If (g.Day = b.Day) Then
                    If (c1 >= 0) Then
                        If (c < 0) Then
                            If (cc1 >= 0) Then
                                If (cc < 0) Then
                                    MessageBox.Show("Début de séquence avant la fin de la précédente minute", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                                    Exit Sub
                                End If
                            End If
                        End If
                    ElseIf (c1 < 0) Then
                        If (cc1 < 0) Then
                            If (cc < 0) Then
                                MessageBox.Show("Début de séquence avant la fin de la précédente heure", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                                Exit Sub
                            ElseIf (cc1 < 0) Then
                                MessageBox.Show("Fin de séquence après début de la précédente heure", "Capteur Abandonné", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                            ElseIf (c1 > 0) Then
                            End If
                        End If
                    End If
                End If
            Next
        Next
        l = j + l
        If (l <= 240) Then disque = 1

        If (l > 240 And l < 480) Then disque = 2

        If (l >= 480) Then disque = 3

        item1.Text = g.ToString         '1°cellule
        item1.SubItems.Add(h.ToString)  '2°
        item1.SubItems.Add(j)           '3°



        If (CheckBox1.Checked = True) Then
            item1.SubItems.Add("oui")
            camera = 0
        Else : item1.SubItems.Add("non")
            camera = 1
        End If
        item1.SubItems.Add(disque)
        ListView1.Items.Add(item1)      'ajout de la ligne

    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Timer2.Stop()

        For i As Integer = ListView1.Items.Count - 1 To 0 Step -1
            If ListView1.SelectedIndices.Contains(i) Then
                m = ListView1.SelectedItems(0).SubItems(2).Text 'recupere le texte dans la 3°colonne de la ligne selectionnée
                l = l - m
                ListView1.Items.RemoveAt(i)

            End If
        Next

    End Sub
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim result As DialogResult
        result = MessageBox.Show("Voulez-vous sauvergarder", "Capteur Abandonné", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)

        If result = Windows.Forms.DialogResult.Yes Then
            Retour = SaveFileDialog1.ShowDialog()
            If Retour = 1 Then
                Dim Dates As String = ""
                Dim i As Integer
                For i = 0 To ListView1.Items.Count - 1
                    Dates = Dates & ListView1.Items(i).SubItems(0).Text & "|" & ListView1.Items(i).SubItems(1).Text & "|" & ListView1.Items(i).SubItems(2).Text & "|" & ListView1.Items(i).SubItems(3).Text & "|" & vbCrLf '& ListView.Items(i).SubItems(4).Text & vbCrLf
                Next i
                FileOpen(1, SaveFileDialog1.FileName, OpenMode.Binary)
                FilePut(1, Dates)
                FileClose(1)
            End If
        ElseIf result = Windows.Forms.DialogResult.No Then
        ElseIf result = Windows.Forms.DialogResult.Cancel Then
            Exit Sub
        End If
        End
    End Sub
    Private Sub AfficherToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AfficherToolStripMenuItem.Click

    End Sub

    Private Sub CacherToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CacherToolStripMenuItem.Click

    End Sub

    Private Sub QuitterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitterToolStripMenuItem.Click
        End
    End Sub
    Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Me.Show()
        Me.ShowInTaskbar = True
    End Sub

    Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label4.Click

    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

    End Sub

    Private Sub ContextMenuStrip1_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip1.Opening

    End Sub

    Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click

    End Sub


    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

        'OUVRIR
        Dim Retour As Integer
        Retour = OpenFileDialog1.ShowDialog()
        If Retour = 1 Then
            FileOpen(1, OpenFileDialog1.FileName, OpenMode.Binary)
            FileClose(1)

            Dim val() As String
            Dim fs As New IO.FileStream(OpenFileDialog1.FileName, IO.FileMode.Open)
            Dim str As New IO.StreamReader(fs)
            Dim lvi As ListViewItem
            Dim i As Integer
            Do Until str.Peek = -1
                val = str.ReadLine.Split("|")
                lvi = ListView1.Items.Add(val(0))
                For i = 1 To val.Length - 1
                    lvi.SubItems.Add(val(i))
                Next
            Loop

            str.Close()
            fs.Close()
        End If
    End Sub
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        'Sauver
        Retour = SaveFileDialog1.ShowDialog()
        If Retour = 1 Then
            Dim Dates As String = ""
            Dim i As Integer
            For i = 0 To ListView1.Items.Count - 1
                Dates = Dates & ListView1.Items(i).SubItems(0).Text & "|" & ListView1.Items(i).SubItems(1).Text & "|" & ListView1.Items(i).SubItems(2).Text & "|" & ListView1.Items(i).SubItems(3).Text & "|" & vbCrLf '& ListView.Items(i).SubItems(4).Text & vbCrLf
            Next i
            FileOpen(1, SaveFileDialog1.FileName, OpenMode.Binary)
            FilePut(1, Dates)
            FileClose(1)
        End If
    End Sub

    Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
        PictureBox2.Hide()
        PictureBox3.Show()
    End Sub


    Private Sub btnEnvoiRéception_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRéception.Click
        'Appel initportcom(nom_du_port_com)
        InitPortCom(Portcom)
        'Envoi de données sur le port com (çà dépend avec qui tu communqiues
        For s As Integer = 0 To ListView1.Items.Count - 1 Step 1
            aa = ListView1.Items(s).Text
            bb = ListView1.Items(s).SubItems(1).Text
            Portcom.Output = aa.Day & aa.Hour & aa.Minute & ListView1.Items(s).SubItems(3).Text & camera & bb.Day & bb.Hour & bb.Minute
            'Portcom.Output = aa.Hour
            'Portcom.Output = aa.Minute
            'Portcom.Output = ListView1.Items(s).SubItems(2).Text
            'Portcom.Output = ListView1.Items(s).SubItems(3).Text
            'Portcom.Output = camera
            'Portcom.Output = bb.Day
            'Portcom.Output = bb.Hour
            'Portcom.Output = bb.Minute
            'SerialPort1.Write(ListView1.Items(s).SubItems(3).Text)
        Next
    End Sub

    'Fonction d'initialisation du Port de Commnication
    Private Sub InitPortCom(ByRef PortdeCom As AxMSCommLib.AxMSComm)
        Dim parité As String
        Try
            'Ferme le port com
            If PortdeCom.PortOpen = True Then
                PortdeCom.PortOpen = False
                'SerialPort1.Open()
            End If
            'Affectation du n° du port com
            PortdeCom.CommPort = CInt(1)
            'Recherche de la parité
            Select Case "Aucun"
                Case "Aucun"
                    parité = "n"
                Case "Impair"
                    parité = "o"
                Case "Pair"
                    parité = "e"
                Case Else
                    MsgBox("Erreur parité")
                    Exit Sub
            End Select
            'Affectation des paramètres de com
            PortdeCom.Settings = 9600 & "," & parité & "," & 8 & "," & 1
            ' Evénement OnComm dès que l'on reçoit des données
            PortdeCom.RThreshold = 1
            ' Force l'utilisation du DTR (utilisés pour raccrocher les modems)
            PortdeCom.DTREnable = True
            ' Pas d'échange de données
            PortdeCom.Handshaking = MSCommLib.HandshakeConstants.comNone
            ' Récupération en texte
            PortdeCom.InputMode = MSCommLib.InputModeConstants.comInputModeText
            ' Récupération de toutes les données lors de la lecture
            PortdeCom.InputLen = 0
            ' Lecture des valeurs nulles
            PortdeCom.NullDiscard = False
            'Ouvrir le portcom
            'Déclaration de l'évènement OnComm pour la réception des mesures
            AddHandler PortdeCom.OnComm, AddressOf LectureEntrée
            PortdeCom.PortOpen = True
        Catch ex As Exception
            MsgBox("Erreur durant l'initialisation du port com" & vbCrLf & vbCrLf & ex.ToString)
        End Try
    End Sub
    'La lecture se fait par interruption interne
    Private Sub LectureEntrée(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lectureportcom As String
        Try
            'Si le buffer du port de com n'est pas vide
            If Portcom.InBufferCount > 0 Then
                'récupération du buffer
                lectureportcom = CType(Portcom.Input, String)
                'affichage
                txtEcoute.Text = txtEcoute.Text & lectureportcom
            End If
        Catch ex As Exception
            MsgBox("Erreur durant la réception" & vbCrLf & vbCrLf & ex.ToString)
        End Try
    End Sub
End Class
