Imports BrightIdeasSoftware
Imports System.Globalization
Imports GPSConnector.Common
Imports GPSConnector.Client.GPSConnectorService
Imports System.ServiceModel
Imports System.Threading

Public Class FrmMain
    Private _deviceLists As List(Of DeviceInfo)
    Private WithEvents _gpsService As GPSConnectorStatusServiceClient
    Private WithEvents _gpsConnectorCallBackHandler As New GPSConnectorCallBackHandler
    Private _instanceContext As New InstanceContext(_gpsConnectorCallBackHandler)
    Private _owner As Owner
    Public Sub Init()
        Dim frmSplashScreen As New FrmSplashScreen
        frmSplashScreen.Show()
        Try
            frmSplashScreen.SetActivity("Initializace...")

            _gpsService = New GPSConnectorStatusServiceClient(_instanceContext)
            _gpsService.ClientCredentials.UserName.UserName = My.Settings.ServiceUserName
            _gpsService.ClientCredentials.UserName.Password = My.Settings.ServicePassword

            frmSplashScreen.SetActivity("Validace klíče...")
            ValidateOwnerKey()


            If _owner.IsAdmin Then

                SetupDeviceDataListView()
                SetupLogListView()
                SetupDeviceComponentListView()
               
                frmSplashScreen.SetActivity("Načitá se terminály...")
                GetDeviceList()
                frmSplashScreen.SetActivity("Načitá se zprávy...")
                GetLog()
                frmSplashScreen.SetActivity("Načitá se komponenty...")
                GetComponents()
                frmSplashScreen.SetActivity("Načitá se ostatní služby...")

            Else
                SetupDeviceDataListView()
                PnlMessageHeaders.Hide()
                SplitterDeviceData.Hide()
                objLvwLog.Hide()
                objLvwDeviceData.Dock = DockStyle.Fill
                TabMain.TabPages.Remove(TpComponent)
                frmSplashScreen.SetActivity("Načitá se terminály...")
                TpMain.Text = "Terminály"
                GetDeviceList()
            End If

            If _owner.CalcDistributors Is Nothing OrElse _owner.CalcDistributors.Count > 0 Then
                cboDistributors.Items.Clear()

                For Each d As Common.Distributor In _owner.CalcDistributors.OrderBy(Function(dd) dd.Name)
                    cboDistributors.Items.Add(d)
                Next

                cboDistributors.SelectedIndex = 0
            Else
                TabMain.TabPages.Remove(TpCalculation)
            End If

            frmSplashScreen.SetActivity("startuje se...")
           
            If _deviceLists.Count > 0 Then
                _gpsService.Subscribe(_owner.Key)
                TmrGPSDeviceStatus.Interval = 1000
                TmrGPSDeviceStatus.Enabled = True
                tmrHeatBeat.Interval = 30000
                tmrHeatBeat.Enabled = True
            End If

            TabMain.SelectTab(TpMain)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Application.Exit()
        Finally
            frmSplashScreen.Close()
        End Try


    End Sub
    Private Sub ReInit()
        Try
            _TmrGPSDeviceStatus.Enabled = False

            butRefreshGPSDeviceData.Enabled = False
            ButRefreshComponent.Enabled = False
            ButRefreshLog.Enabled = False
            
            _gpsConnectorCallBackHandler = New GPSConnectorCallBackHandler
            _instanceContext = New InstanceContext(_gpsConnectorCallBackHandler)
            _gpsService = New GPSConnectorStatusServiceClient(_instanceContext)
            _gpsService.ClientCredentials.UserName.UserName = My.Settings.ServiceUserName
            _gpsService.ClientCredentials.UserName.Password = My.Settings.ServicePassword
            _gpsService.Subscribe(_owner.Key)

            GetDeviceList(False)
            GetLog(False)
            GetComponents(False)

            _TmrGPSDeviceStatus.Enabled = True
            butRefreshGPSDeviceData.Enabled = True
            ButRefreshComponent.Enabled = True
            ButRefreshLog.Enabled = True

        Catch ex As Exception
            lblDeviceDataProgress.Text = "Klient je odpojený. Automatické připojení se nezdařilo. Restartujte aplikaci."
            lblDeviceDataProgress.Visible = True
        Finally
            
        End Try

    End Sub

    Private Sub ValidateOwnerKey()
        If String.IsNullOrEmpty(My.Settings.OwnerKey) OrElse My.Settings.OwnerKey.Trim().Length = 0 Then
            Throw New Exception("Neplatný klíč. kontaktujte servis-net")
        End If
        _owner = _gpsService.GetOwnerInfo(My.Settings.OwnerKey)

        If _owner Is Nothing Then
            Throw New Exception("Neplatný klíč. kontaktujte servis-net")
        End If

    End Sub

   Private Sub SetupDeviceComponentListView()
        With objLvwComponent
            .AllColumns.Clear()
            .Columns.Clear()
            .ShowGroups = False
            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "Typ přístroje", _
                            .AspectGetter = Function(o As DeviceTypeComponentInfo) o.DeviceTypeName, _
                            .DisplayIndex = 0, _
                           .IsEditable = False, _
                           .MinimumWidth = 70
                          })
            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "IP", _
                            .AspectGetter = Function(o As DeviceTypeComponentInfo) o.ListenIp, _
                            .DisplayIndex = 1, _
                           .IsEditable = False, _
                           .MinimumWidth = 50
                          })

            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "Port", _
                            .AspectGetter = Function(o As DeviceTypeComponentInfo) o.ListenPort, _
                            .DisplayIndex = 2, _
                           .IsEditable = False, _
                           .MinimumWidth = 50
                          })

            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "Počet aktvních spojení", _
                            .AspectGetter = Function(o As DeviceTypeComponentInfo) o.ActiveConnectionCount, _
                            .DisplayIndex = 3, _
                           .IsEditable = False, _
                           .MinimumWidth = 110
                          })
            .FullRowSelect = True
            .RebuildColumns()
        End With
    End Sub
    Private Sub SetupLogListView()
        With objLvwLog
            .AllColumns.Clear()
            .Columns.Clear()
            .ShowGroups = False
            .AllColumns.Add(New OLVColumn() With _
                            { _
                             .Text = "Typ", _
                             .Tag = "type", _
                             .AspectGetter = Function(o As LogInfo) If(o.LogType = EnLogInfoType.Error, "Chyba", "Info"), _
                             .DisplayIndex = 0, _
                            .IsEditable = False, _
                            .MinimumWidth = 50
                           })

            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "Datum", _
                            .AspectGetter = Function(o As LogInfo) o.LogDate.ToString("dd.MM.yyyy HH:mm:ss"), _
                            .DisplayIndex = 1, _
                           .IsEditable = False, _
                           .MinimumWidth = 80
                          })
            .AllColumns.Add(New OLVColumn() With _
                          { _
                           .Text = "Vlastník", _
                           .AspectGetter = Function(o As LogInfo) o.Owner, _
                           .DisplayIndex = 2, _
                          .IsEditable = False, _
                          .MinimumWidth = 60
                         })
            .AllColumns.Add(New OLVColumn() With _
                         { _
                          .Text = "Zpráva", _
                          .AspectGetter = Function(o As LogInfo) o.Log, _
                          .DisplayIndex = 3, _
                         .IsEditable = False, _
                         .MinimumWidth = 250, _
                         .WordWrap = True
                        })
            .FullRowSelect = True
            .RebuildColumns()

        End With
    End Sub
    Private Sub SetupDeviceDataListView()
        With objLvwDeviceData
            .AllColumns.Clear()
            .Columns.Clear()
            .ShowGroups = False

            .AllColumns.Add(New OLVColumn() With _
                            { _
                             .Text = "ID", _
                                .Tag = "id", _
                             .AspectGetter = Function(o As DeviceInfo) o.GPSDevice.Id, _
                             .DisplayIndex = 0, _
                            .IsEditable = False, _
                            .MinimumWidth = 50
                           })

            .AllColumns.Add(New OLVColumn() With _
                            { _
                             .Text = "Timer", _
                                .Tag = "timer", _
                             .AspectGetter = Function(o As DeviceInfo) o.TimerFormat, _
                             .DisplayIndex = 1, _
                            .IsEditable = False, _
                            .MinimumWidth = 50
                           })

            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "IMEI", _
                            .AspectGetter = Function(o As DeviceInfo) Microsoft.VisualBasic.Right(o.GPSDevice.Imei, 6), _
                            .DisplayIndex = 2, _
                           .IsEditable = False, _
                           .MinimumWidth = 50
                          })
            .AllColumns.Add(New OLVColumn() With _
                             { _
                              .Text = "Code", _
                              .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.MessageCode, _
                              .DisplayIndex = 3, _
                             .IsEditable = False, _
                             .MinimumWidth = 50
                             })
            .AllColumns.Add(New OLVColumn() With _
                             { _
                              .Text = "Cause", _
                              .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.LoggingCause, _
                              .DisplayIndex = 4, _
                             .IsEditable = False, _
                             .MinimumWidth = 50
                             })
            .AllColumns.Add(New OLVColumn() With _
                               { _
                                .Text = "Čas posl. zprávy", _
                                .AspectGetter = Function(o As DeviceInfo) ConvertToLocalTime(o.GPSDeviceData.LoggingTime), _
                                .DisplayIndex = 5, _
                               .IsEditable = False, _
                               .MinimumWidth = 70
                              })


            .AllColumns.Add(New OLVColumn() With _
                             { _
                              .Text = "LT", _
                              .AspectGetter = Function(o As DeviceInfo) ConvertToDegreeMinutesSecond(o.GPSDeviceData.Latitude), _
                              .DisplayIndex = 6, _
                             .IsEditable = False, _
                             .MinimumWidth = 50
                             })
            .AllColumns.Add(New OLVColumn() With _
                            { _
                             .Text = "LD", _
                             .AspectGetter = Function(o As DeviceInfo) ConvertToDegreeMinutesSecond(o.GPSDeviceData.Longtitude), _
                             .DisplayIndex = 7, _
                            .IsEditable = False, _
                            .MinimumWidth = 50
                            })
            .AllColumns.Add(New OLVColumn() With _
                           { _
                            .Text = "FIX", _
                            .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.FixType & "-D", _
                            .DisplayIndex = 8, _
                           .IsEditable = False, _
                           .MinimumWidth = 50
                           })
            .AllColumns.Add(New OLVColumn() With _
                          { _
                           .Text = "HD", _
                           .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.Course, _
                           .DisplayIndex = 9, _
                          .IsEditable = False, _
                          .MinimumWidth = 50
                          })

            .AllColumns.Add(New OLVColumn() With _
                       { _
                        .Text = "HG", _
                        .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.Height, _
                        .DisplayIndex = 10, _
                       .IsEditable = False, _
                       .MinimumWidth = 50
                       })

            .AllColumns.Add(New OLVColumn() With _
                       { _
                        .Text = "R", _
                        .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.Speed, _
                        .DisplayIndex = 11, _
                       .IsEditable = False, _
                       .MinimumWidth = 50
                       })
            .AllColumns.Add(New OLVColumn() With _
                     { _
                      .Text = "SAT", _
                      .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.SatellitesViewed.ToString("00") + "/24", _
                      .DisplayIndex = 12, _
                     .IsEditable = False, _
                     .MinimumWidth = 40
                     })
            .AllColumns.Add(New OLVColumn() With _
                      { _
                       .Text = "DI", _
                       .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.DigIN, _
                       .DisplayIndex = 13, _
                      .IsEditable = False, _
                      .MinimumWidth = 50
                      })
            .AllColumns.Add(New OLVColumn() With _
                      { _
                       .Text = "DO", _
                       .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.DigOUT, _
                       .DisplayIndex = 14, _
                      .IsEditable = False, _
                      .MinimumWidth = 50
                      })
            .AllColumns.Add(New OLVColumn() With _
                      { _
                       .Text = "AI", _
                       .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.AnlgIN, _
                       .DisplayIndex = 15, _
                      .IsEditable = False, _
                      .MinimumWidth = 50
                      })

            .AllColumns.Add(New OLVColumn() With _
                     { _
                      .Text = "AO", _
                      .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.AnlgOUT, _
                      .DisplayIndex = 16, _
                     .IsEditable = False, _
                     .MinimumWidth = 50
                     })
            .AllColumns.Add(New OLVColumn() With _
                               { _
                                .Text = "IP", _
                                .AspectGetter = Function(o As DeviceInfo) o.GPSDeviceData.IP, _
                                .DisplayIndex = 17, _
                               .IsEditable = False, _
                               .MinimumWidth = 50
                              })
            .AllColumns.Add(New OLVColumn() With _
                               { _
                                .Text = "Název terminálu", _
                                .AspectGetter = Function(o As DeviceInfo) o.GPSDevice.DeviceName, _
                                .DisplayIndex = 18, _
                               .IsEditable = False, _
                               .MinimumWidth = 50
                              })
            .GridLines = True
            .FullRowSelect = True
            .RebuildColumns()
        End With
    End Sub
    Private Sub GetDeviceList(Optional showError As Boolean = True)
        Try
            If lblDeviceDataProgress.InvokeRequired Then
                lblDeviceDataProgress.Invoke(Sub() lblDeviceDataProgress.Visible = True)
            Else
                lblDeviceDataProgress.Visible = True
            End If

            If butRefreshGPSDeviceData.InvokeRequired Then
                butRefreshGPSDeviceData.Invoke(Sub() butRefreshGPSDeviceData.Enabled = False)
            Else
                butRefreshGPSDeviceData.Enabled = False
            End If

            Dim devices As List(Of GPSDevice) = _gpsService.GetDevices(_owner.Key)
            Dim gpsDeviceDatas As List(Of GPSDeviceData) = _gpsService.GetDeviceData(_owner.Key)

            _deviceLists = New List(Of DeviceInfo)()
            If devices Is Nothing OrElse devices.Count = 0 Then
                Throw New Exception("Není definován žádný terminál. Kontaktujte admina")
            End If


            For Each gpsDevice As GPSDevice In devices
                Dim gpsdeviceInfo As New DeviceInfo(gpsDevice)

                For Each gpsDeviceData As GPSDeviceData In gpsDeviceDatas
                    If gpsDeviceData.Id = gpsDevice.Id Then
                        gpsdeviceInfo.GPSDeviceData = gpsDeviceData
                        Exit For
                    End If
                Next

                _deviceLists.Add(gpsdeviceInfo)
            Next

            _deviceLists = _deviceLists.OrderBy(Function(d) d.GPSDevice.Id).ToList()

            If objLvwDeviceData.InvokeRequired Then
                objLvwDeviceData.Invoke(Sub() objLvwDeviceData.SetObjects(_deviceLists))
                ' objLvwDeviceData.Invoke(Sub() objLvwDeviceData.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent))
            Else
                objLvwDeviceData.SetObjects(_deviceLists)
                ' objLvwDeviceData.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            End If



        Catch ex As Exception
            If showError Then
                MessageBox.Show(ex.Message, "Terminály : Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        Finally
            If lblDeviceDataProgress.InvokeRequired Then
                lblDeviceDataProgress.Invoke(Sub() lblDeviceDataProgress.Visible = False)
            Else
                lblDeviceDataProgress.Visible = False
            End If

            If butRefreshGPSDeviceData.InvokeRequired Then
                butRefreshGPSDeviceData.Invoke(Sub() butRefreshGPSDeviceData.Enabled = True)
            Else
                butRefreshGPSDeviceData.Enabled = True
            End If
        End Try

    End Sub

    Private Sub GetLog(Optional showError As Boolean = True)
        Try
            If lblLogProgress.InvokeRequired Then
                lblLogProgress.Invoke(Sub() lblLogProgress.Visible = True)
            Else
                lblLogProgress.Visible = True
            End If

            If ButRefreshLog.InvokeRequired Then
                ButRefreshLog.Invoke(Sub() ButRefreshLog.Enabled = False)
            Else
                ButRefreshLog.Enabled = False
            End If

            Dim logInfos As List(Of LogInfo) = _gpsService.GetLogInfo()
            Dim logErrors As List(Of LogInfo) = _gpsService.GetLogInfo()

            Dim allInfo As New List(Of LogInfo)
            If Not logInfos Is Nothing AndAlso logInfos.Count > 0 Then
                allInfo.AddRange(logInfos)
            End If

            If Not logErrors Is Nothing AndAlso logErrors.Count > 0 Then
                allInfo.AddRange(logErrors)
            End If
            allInfo = allInfo.OrderByDescending(Function(a) a.LogDate).ToList()

            If objLvwLog.InvokeRequired Then
                objLvwLog.Invoke(Sub() objLvwLog.SetObjects(allInfo))
                'objLvwLog.Invoke(Sub() objLvwLog.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent))
            Else
                objLvwLog.SetObjects(allInfo)
                ' objLvwLog.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            End If

        Catch ex As Exception
            If showError Then
                MessageBox.Show(ex.Message, "Log : ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Finally
            If lblLogProgress.InvokeRequired Then
                lblLogProgress.Invoke(Sub() lblLogProgress.Visible = False)
            Else
                lblLogProgress.Visible = False
            End If

            If ButRefreshLog.InvokeRequired Then
                ButRefreshLog.Invoke(Sub() ButRefreshLog.Enabled = True)
            Else
                ButRefreshLog.Enabled = True
            End If
        End Try


    End Sub

    Private Sub GetComponents(Optional showError As Boolean = True)
        Try
            If lblComponentProgress.InvokeRequired Then
                lblComponentProgress.Invoke(Sub() lblComponentProgress.Visible = True)
            Else
                lblComponentProgress.Visible = True
            End If

            If ButRefreshComponent.InvokeRequired Then
                ButRefreshComponent.Invoke(Sub() ButRefreshComponent.Enabled = False)
            Else
                ButRefreshComponent.Enabled = False
            End If


            Dim devicecomponents As List(Of DeviceTypeComponentInfo) = _gpsService.GetDeviceTypeComponentInfo()

            If objLvwComponent.InvokeRequired Then
                objLvwComponent.Invoke(Sub() objLvwComponent.SetObjects(devicecomponents))
                ' objLvwComponent.Invoke(Sub() objLvwComponent.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent))
            Else
                objLvwComponent.SetObjects(devicecomponents)
                ' objLvwComponent.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            End If


        Catch ex As Exception
            If showError Then
                MessageBox.Show(ex.Message, "Components : ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Finally
            If lblComponentProgress.InvokeRequired Then
                lblComponentProgress.Invoke(Sub() lblComponentProgress.Visible = False)
            Else
                lblComponentProgress.Visible = False
            End If

            If ButRefreshComponent.InvokeRequired Then
                ButRefreshComponent.Invoke(Sub() ButRefreshComponent.Enabled = True)
            Else
                ButRefreshComponent.Enabled = True
            End If

        End Try

    End Sub

   
    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
        Dim frmAbout As New FrmAbout
        frmAbout.ShowDialog()
    End Sub

    Private Sub GPSConnectorCallBackHandler_NewDeviceDataArrival(data As GPSDeviceData) Handles _gpsConnectorCallBackHandler.NewDeviceDataArrival
        Try
            For Each deviceInfo As DeviceInfo In _deviceLists
                If deviceInfo.GPSDevice.Id = data.Id Then
                    deviceInfo.GPSDeviceData = data
                    Exit Sub
                End If
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
      
    End Sub

    Private Sub GPSConnectorCallBackHandler_NewLogInfoArrival(logInfo As LogInfo) Handles _gpsConnectorCallBackHandler.NewLogInfoArrival
        If _owner.IsAdmin Then
            objLvwLog.InsertObjects(0, New List(Of LogInfo)() From {logInfo})
            'objLvwLog.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            objLvwLog.RefreshObject(logInfo)
        End If
    End Sub

    Private Sub ButRefreshGPSDeviceData_Click(sender As System.Object, e As EventArgs) Handles butRefreshGPSDeviceData.Click
        Try
            Dim t As New Thread(New ThreadStart(AddressOf GetDeviceList))
            t.Start()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try
    End Sub

    Private Sub ButRefreshLog_Click(sender As System.Object, e As EventArgs) Handles ButRefreshLog.Click
        Try
            Dim t As New Thread(New ThreadStart(AddressOf GetLog))
            t.Start()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ButRefreshComponent_Click(sender As System.Object, e As EventArgs) Handles ButRefreshComponent.Click
        Try
            Dim t As New Thread(New ThreadStart(AddressOf GetComponents))
            t.Start()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub ButCalculate_Click(sender As System.Object, e As EventArgs) Handles ButCalculate.Click
        Try
            ButCalculate.Enabled = False
            lblCalculateStatus.Text = "Čekejte prosím..."
            lblCalculateStatus.ForeColor = Color.Red
            lblCalculateStatus.Visible = True
            cboDistributors.Enabled = False
            dtpDataDate.Enabled = False
            Dim distributor As Common.Distributor = cboDistributors.SelectedItem
            _gpsService.CalculateAsync(_owner.Key, distributor.Id, dtpDataDate.Value)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        Init()
    End Sub
 Private Sub objLvwDeviceData_FormatCell(sender As Object, e As FormatCellEventArgs) Handles objLvwDeviceData.FormatCell
        Try
            If Not e.Column.Tag Is Nothing AndAlso e.Column.Tag.ToString() = "id" Then
                e.SubItem.Font = New Font(e.SubItem.Font, e.SubItem.Font.Style Or FontStyle.Bold)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
       
    End Sub

    Private Sub objLvwDeviceData_FormatRow(sender As Object, e As FormatRowEventArgs) Handles objLvwDeviceData.FormatRow
        Try
            e.UseCellFormatEvents = True
            Dim dnfo As DeviceInfo = CType(e.Model, DeviceInfo)
            e.Item.BackColor = dnfo.StatusColor
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

  Private Sub objLvwLog_FormatCell(sender As Object, e As FormatCellEventArgs) Handles objLvwLog.FormatCell
        Try
            If Not e.Column.Tag Is Nothing AndAlso e.Column.Tag.ToString() = "type" Then
                Dim model As LogInfo = CType(e.Model, LogInfo)
                If model.LogType = EnLogInfoType.Error Then
                    e.SubItem.ForeColor = Color.Red
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
        
    End Sub

    Private Sub objLvwLog_FormatRow(sender As Object, e As FormatRowEventArgs) Handles objLvwLog.FormatRow
        e.UseCellFormatEvents = True
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles SettingsToolStripMenuItem.Click
        Try
            Dim frmSettings As New FrmSettings
            frmSettings.ShowDialog()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
       

    End Sub

    Private Sub TmrGPSDeviceStatus_Tick(sender As Object, e As EventArgs) Handles TmrGPSDeviceStatus.Tick
        Try
            For Each device In _deviceLists
                device.Timer += 1
            Next
            objLvwDeviceData.RefreshObjects(_deviceLists)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    Private Function ConvertToLocalTime(d As String) As String
      Try
            Return Date.ParseExact(d, "ddMMyyHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToLocalTime().ToString("dd.MM.yyyy HH:mm:ss")
        Catch ex As Exception
            Return "00.00.00 00:00:00"
        End Try
    End Function

    Private Function ConvertToDegreeMinutesSecond(d As String) As String
        Dim degree As String = d.Substring(0, 2) & "°"
        Dim minutes As String = (Double.Parse("0." & d.Substring(2), CultureInfo.InvariantCulture) * 60).ToString("00.000", CultureInfo.GetCultureInfo("cs-CZ")) & "'"

        Return degree & minutes
    End Function

    Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub

    Private Sub tmrHeatBeat_Tick(sender As Object, e As EventArgs) Handles tmrHeatBeat.Tick
        Try
            _gpsService.HeartBeatTest()
        Catch ex As Exception
            ReInit()
        End Try
    End Sub
    Private Sub _gpsService_CalculateCompleted(sender As Object, e As CalculateCompletedEventArgs) Handles _gpsService.CalculateCompleted
        Try
            ButCalculate.Enabled = True
            If e.Result.Success Then
                lblCalculateStatus.Text = "Kalkulace skončila úspěšně"
                lblCalculateStatus.ForeColor = Color.Green
            Else
                lblCalculateStatus.Text = "Kalkulace skončila chybou"
                lblCalculateStatus.ForeColor = Color.Red
            End If

            lblCalculateStatus.Visible = True
            cboDistributors.Enabled = True
            dtpDataDate.Enabled = True
            txtCalculationResult.Text = e.Result.Log
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class
