Imports System.Globalization
Imports System.Configuration
Imports GPSConnector.Common
Imports System.IO
Imports System.Text
Imports System.Data.SqlClient

Public Class GPSDeviceDataPersistence
    Implements IGPSDeviceDataPersistence
    Private ReadOnly _storedLocationPath As String
    Private ReadOnly _logger As IGPSLogger
    Private ReadOnly _storedGslocLocationPath As String
    Private ReadOnly _connectionString As String
    Public Sub Persist(deviceTypeName As String, data As GPSDeviceData) Implements IGPSDeviceDataPersistence.Persist
        Try
            If ConfigurationManager.AppSettings("SaveGSLOC") = "true" Then
                SaveGSLOC(data)
            End If
        Catch ex As Exception
            _logger.LogException(ex, "GPSDeviceDataPersistence:SaveGSLOC", True, True)
        End Try

        Try
            SaveSQL(data)
        Catch ex As Exception
            _logger.LogException(ex, "GPSDeviceDataPersistence:SaveSQL", True, True)
        End Try

    End Sub

    Public Sub New(storedLocationPath As String, storedGslocLocationPath As String, ByVal logger As IGPSLogger, connectionStringName As String)
        _storedLocationPath = storedLocationPath
        _storedGslocLocationPath = storedGslocLocationPath
        _logger = logger
        If Not Directory.Exists(_storedLocationPath) Then
            Directory.CreateDirectory(_storedLocationPath)
        End If

        If Not Directory.Exists(_storedGslocLocationPath) Then
            Directory.CreateDirectory(_storedGslocLocationPath)
        End If
        _connectionString = ConfigurationManager.ConnectionStrings(connectionStringName).ConnectionString
    End Sub
    Private Sub SaveGSLOC(data As GPSDeviceData)
        Dim gsloc As GsLoc = GPSDeviceDataToGsLoc(data)
        Dim loggingDate As Date = Date.ParseExact(String.Format("{0} {1}", gsloc.Datum2, gsloc.Cas2), "dd.MM.yy HH:mm:ss", CultureInfo.GetCultureInfo("cs-CZ"), DateTimeStyles.AssumeUniversal).ToLocalTime()
        Dim filename As String = Path.Combine(_storedGslocLocationPath, String.Format("PT_GPRS_{0}.txt", loggingDate.ToString("yyyyMMdd")))
        Using fs As FileStream = New FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
            Using w As StreamWriter = New StreamWriter(fs, Encoding.ASCII)
                w.WriteLine(gsloc.ToString())
                w.Flush()
                w.Close()
            End Using
        End Using
    End Sub

    Private Sub SaveSQL(data As GPSDeviceData)
        Dim logginCause As Integer

        'If (Integer.TryParse(data.FixType, fixTyp) AndAlso fixTyp < 3) Then
        '    Return
        'End If
        'If Not (data.MessageCode = "20" OrElse data.MessageCode = "21" OrElse data.MessageCode = "30" OrElse data.MessageCode = "31") Then
        '    Return
        'End If
        If String.IsNullOrEmpty(data.Longtitude) OrElse String.IsNullOrEmpty(data.Latitude) Then
            Return
        End If

        If Not (Integer.TryParse(data.LoggingCause, logginCause)) Then
            data.LoggingCause = "98"
        End If
        Dim sqlConnection As New SqlConnection(_connectionString)

        Try

            sqlConnection.Open()
            Using cmd As New SqlCommand()
                With cmd
                    .Connection = sqlConnection
                    .CommandText = "dbo.sp_gps_device_data_ins"
                    .CommandType = CommandType.StoredProcedure
                    .Parameters.AddWithValue("@gps_device_id", data.Id)
                    .Parameters.AddWithValue("@received_date", Date.ParseExact(data.ReceivedDate, "dd.MM.yy", CultureInfo.GetCultureInfo("cs-CZ"), DateTimeStyles.AssumeLocal).Date)
                    .Parameters.AddWithValue("@received_time", Date.ParseExact(data.ReceivedTime, "HH:mm:ss", CultureInfo.GetCultureInfo("cs-CZ"), DateTimeStyles.AssumeLocal).TimeOfDay)
                    .Parameters.AddWithValue("@gps_date", Date.ParseExact(data.LoggingTime, "ddMMyyHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).Date)
                    .Parameters.AddWithValue("@gps_time", Date.ParseExact(data.LoggingTime, "ddMMyyHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).TimeOfDay)
                    .Parameters.AddWithValue("@longitude", data.Longtitude.Replace(CultureInfo.InvariantCulture.NumberFormat.NumberGroupSeparator, String.Empty).Replace(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, String.Empty))
                    .Parameters.AddWithValue("@latitude", data.Latitude.Replace(CultureInfo.InvariantCulture.NumberFormat.NumberGroupSeparator, String.Empty).Replace(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, String.Empty))
                    .Parameters.AddWithValue("@altitude", data.Height)
                    .Parameters.AddWithValue("@speed", data.Speed)
                    .Parameters.AddWithValue("@course", data.Course)
                    .Parameters.AddWithValue("@satelite_in_viewed", data.SatellitesViewed)
                    .Parameters.AddWithValue("@analog_in", data.AnlgIN)
                    .Parameters.AddWithValue("@analog_out", data.AnlgOUT)
                    .Parameters.AddWithValue("@digital_in", data.DigIN)
                    .Parameters.AddWithValue("@digital_out", data.DigOUT)
                    .Parameters.AddWithValue("@ip", If(String.IsNullOrEmpty(data.IP), String.Empty, data.IP))
                    .Parameters.AddWithValue("@exact_received_date", data.ExactReceivedDate)
                    .Parameters.AddWithValue("@message_code", Integer.Parse(data.MessageCode))
                    .Parameters.AddWithValue("@logging_cause", Integer.Parse(data.LoggingCause))
                    .ExecuteNonQuery()
                End With

                sqlConnection.Close()
            End Using
        Finally
            sqlConnection.Close()
            sqlConnection.Dispose()
        End Try

    End Sub

End Class
