' NOTE: You can use the "Rename" command on the context menu to change the class name "i3Screen" in code, svc and config file together.
' NOTE: In order to launch WCF Test Client for testing this service, please select i3Screen.svc or i3Screen.svc.vb at the Solution Explorer and start debugging.
Imports System.Data.SqlClient
Imports System.Net
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports i3Screen

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
<ServiceBehavior([Namespace]:="https://www.comptechweb.com/WebServices/i3Screen/")>
Public Class i3Screen
    Implements Ii3Screen


    'Public Function authenticate_sso(data As String) As String Implements Ii3Screen.authenticate_sso
    '    Throw New NotImplementedException()
    'End Function


    'Public Function AuthenticateToken(data As String) As String Implements Ii3Screen.AuthenticateToken
    '    Throw New NotImplementedException()
    'End Function


    Public Function BackgroundReports(params As Ii3Screen.BackgroundReportsIn) As Ii3Screen.BackgroundReportsOut Implements Ii3Screen.BackgroundReports
        Dim logId As Integer = 0
        Try

            Dim userid = params.userid
            Dim password = params.password
            Dim data = params.data

            Using connection As New SqlConnection(My.Settings.i3Screen_TestConnection)
                connection.Open()

                ' Log the data received
                logId = LogCommunication(connection, "BackgroundReports", data)

                ' Validate our stuff
                If userid <> My.Settings.i3Screen_TestUserId Or password <> My.Settings.i3Screen_TestPassword Then
                    HttpContext.Current.Response.StatusCode = HttpStatusCode.Unauthorized
                    LogCommunication(connection, logId, "Failure - Invalid UserId or Password")
                    Return New Ii3Screen.BackgroundReportsOut("Failure", "Invalid UserId or Password")
                End If

                ' We'll want to do something with the parsed data here.
                Dim response = "Success"
                Try
                    Call New BackgroundReportUpdate(data).Save(connection)
                Catch ex As EmailedError
                    ex.SendNotification(connection)
                    Throw
                End Try

                ' Log what we are sending back and return
                LogCommunication(connection, logId, response)
                Return New Ii3Screen.BackgroundReportsOut(response)

            End Using

        Catch ex As Exception
            Dim errorId = Logic.Error.Log(My.Settings.i3Screen_TestConnection, ex)
            LogCommunication(logId, "Failure - ref#: " & errorId)
            Return New Ii3Screen.BackgroundReportsOut("Failure", "ref#: " & errorId)
        End Try
    End Function


    Public Function HelloWorld(params As Ii3Screen.HelloWorldIn) As Ii3Screen.HelloWorldOut Implements Ii3Screen.HelloWorld

        Dim name = params.name

        Using connection As New SqlConnection(My.Settings.i3Screen_TestConnection)
            connection.Open()

            ' Log the data received
            Dim logId = LogCommunication(connection, "HelloWorld", name)

            ' Parse the data
            Dim xml = <HelloWorld>Hello, <%= name %>.</HelloWorld>
            Dim response = "<?xml version=""1.0"" encoding=""UTF-8""?>" & xml.ToString()

            ' Log what we are sending back and return
            LogCommunication(connection, logId, response)
            Return New Ii3Screen.HelloWorldOut(response)

        End Using
    End Function


#Region "Helpers"
    
    ' Logs the incoming communication and returns an id of the entry in the log
    Private Function LogCommunication(connection As SqlConnection, method As String, payload As String) As Integer
        Dim cmd As New SqlCommand("
            INSERT INTO i3ScreenLog (timestamp, direction, method, payload)
            VALUES (GETDATE(), 'in', @method, @payload);
            SELECT @@IDENTITY;", connection)
        cmd.Parameters.AddWithValue("method", method)
        cmd.Parameters.AddWithValue("payload", payload)
        Return cmd.ExecuteScalar()
    End Function
    
    ' Update a log entry with our response
    Private Sub LogCommunication(connection As SqlConnection, logId As Integer, response As String)
        Dim cmd As New SqlCommand(
            "UPDATE i3ScreenLog SET response=@response WHERE id=@logId",
            connection)
        cmd.Parameters.AddWithValue("logId", logId)
        cmd.Parameters.AddWithValue("response", response)
        cmd.ExecuteNonQuery()
    End Sub

    Private Sub LogCommunication(logId As Integer, response As String)
        Using connection As New SqlConnection(My.Settings.i3Screen_LiveConnection)
            connection.Open()
            LogCommunication(connection, logId, response)
        End Using
    End Sub

#End Region

End Class
