'/***************************************************************************/
'/**                                                                       **/
'/**                               MAGICARD                                **/
'/**                                                                       **/
'/***************************************************************************/
'/**                                                                       **/
'/**  PROJECT      : SDK VB Demo - Ultima Printers                         **/
'/**                                                                       **/
'/**  MODULE NAME  : Printer.vb                                            **/
'/**                                                                       **/
'/**  COPYRIGHT    : Magicard                                              **/
'/**                                                                       **/
'/***************************************************************************/
Imports System.Net

Partial Public Class Main

#Region "=== Initialisation ==="

    Private Sub InitPrinterTab()
        InitSessionConfigCombo()
        InitErrorResponseCombo()
        InitMoveCardCombo()
        InitEjectModeCombo()
        InitIPModeCombo()

        Dim myFileVersionInfo As FileVersionInfo = FileVersionInfo.GetVersionInfo("SDKShim.dll")
        PrinterMsgBox.AppendText("Demo Version: " + Application.ProductVersion + Environment.NewLine)
        PrinterMsgBox.AppendText(myFileVersionInfo.FileDescription + " Version: " + myFileVersionInfo.FileVersion + Environment.NewLine)
        PrinterMsgBox.AppendText(SDK.ID_SDKBits().ToString + " Bit SDK" + Environment.NewLine + Environment.NewLine)
    End Sub

#End Region

    '*********************************************************************

#Region "=== Local Methods ==="

    Private Sub PrinterGetRadio_CheckedChanged(sender As System.Object, e As System.EventArgs) _
                Handles PrinterGetRadio.CheckedChanged
        PrinterTabGetSetControls(False)
    End Sub

    Private Sub PrinterSetRadio_CheckedChanged(sender As System.Object, e As System.EventArgs) _
                Handles PrinterSetRadio.CheckedChanged
        PrinterTabGetSetControls(True)
    End Sub

    Private Function PrinterActionIsGet() As Boolean
        Return PrinterGetRadio.Checked
    End Function

    Private Sub ClearPrinterMsgButton_Click(sender As System.Object, e As System.EventArgs) Handles ClearPrinterMsgButton.Click
        PrinterMsgBox.Clear()
    End Sub

    Private Sub PrinterTabGetSetControls(State As Boolean)
        If hSession Then
            EjectModeCombo.Enabled = State
            IPModeCombo.Enabled = State
            IPAddressBox.Enabled = State
            IPSubnetBox.Enabled = State
            IPGatewayBox.Enabled = State
        End If
    End Sub

    Private Sub EnableControls(State As Boolean)
        MoveCardButton.Enabled = State
        MoveCardCombo.Enabled = State
        CleanPrinterButton.Enabled = State

        PrintTestCardButton.Enabled = State
        RestartButton.Enabled = State
        ErrorResponseButton.Enabled = State
        ErrorResponseCombo.Enabled = State
        PrinterGetRadio.Enabled = State
        PrinterSetRadio.Enabled = State
        EjectModeButton.Enabled = State
        IPSettingsButton.Enabled = State

        PrinterTabGetSetControls(PrinterGetRadio.Checked = False)

        If State Then
            TabControl.Controls.Add(Information)
            TabControl.Controls.Add(Encoding)
            TabControl.Controls.Add(Driver1)
            TabControl.Controls.Add(Driver2)
            TabControl.Controls.Add(PrintDemo)
        Else
            TabControl.Controls.Remove(Information)
            TabControl.Controls.Remove(Encoding)
            TabControl.Controls.Remove(Driver1)
            TabControl.Controls.Remove(Driver2)
            TabControl.Controls.Remove(PrintDemo)
        End If
    End Sub

    'Private Function PrinterIsReady() As Boolean
    '    Return (SDK.ID_PrinterStatus(hSession) = SDK.PrinterStatus.Ready)
    'End Function

    Private Function PrinterConnected() As Boolean
        Dim temp_string As String = ""
        Select Case SDK.ID_PrinterStatus(hSession)
            Case SDK.PrinterStatus.Ready : Return True
            Case SDK.PrinterStatus.Offline : temp_string = "Printer is offline"
            Case SDK.PrinterStatus.Error : temp_string = "Printer is in error"
            Case SDK.PrinterStatus.Busy : temp_string = "Printer is busy"
        End Select
        MessageBox.Show(temp_string, "Invalid Printer", MessageBoxButtons.OK)
        Return False
    End Function

#End Region

    '*********************************************************************

#Region "=== Open Session ==="
    Dim openconfigkp As New Dictionary(Of SDK.Config, String) From
    {
        {SDK.Config.Normal, "Config Normal"},
        {SDK.Config.Quiet, "Config Quiet"}
    }

    Private Sub InitSessionConfigCombo()
        SessionConfigCombo.DataSource = New BindingSource(openconfigkp, Nothing)
        SessionConfigCombo.DisplayMember = "Value"
        SessionConfigCombo.ValueMember = "Key"
    End Sub

    Private Sub OpenSessionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles OpenSessionButton.Click
        pd.PrinterSettings = ps
        pd.AllowPrintToFile = True
        If pd.ShowDialog() = DialogResult.OK Then

            ps = pd.PrinterSettings

            g = ps.CreateMeasurementGraphics()
            hDC = g.GetHdc()

            Dim SDKReturn As SDK.Return = SDK.ID_OpenSession(hDC, hSession, SessionConfigCombo.SelectedItem.Key)
            If SDKReturn <> SDK.Return.Success Then
                HandleError("OpenSession", SDKReturn)
            Else
                ResinAreaWidthUpDown.Maximum = SDK.ID_CardWidth(hSession)

                If SDK.ID_PrinterType(hSession) <> SDK.PrinterType.Ultima Then
                    MessageBox.Show("Only Valid for Ultima Printers", "Invalid Printer", MessageBoxButtons.OK)
                    SDK.ID_CloseSession(hSession)

                ElseIf Not pd.PrintToFile And Not PrinterConnected() Then
                    CloseSessionButton_Click(sender, e)

                Else
                    PrinterID.Text = "Printer: " + pd.PrinterSettings.PrinterName
                    PrinterID.Visible = True
                    PrinterPrefs.Visible = True

                    Cursor.Current = Cursors.WaitCursor
                    MoveCardButton.Visible = True
                    MoveCardCombo.Visible = True

                    If Not pd.PrintToFile Then
                        Dim ipData As New SDK.IPData
                        GetIPSettings(ipData)

                        IPModeCombo.Enabled = True
                        IPAddressBox.Enabled = True
                        IPSubnetBox.Enabled = True
                        IPGatewayBox.Enabled = True
                    End If

                    OpenSessionButton.Visible = False
                    SessionConfigCombo.Visible = False
                    CloseSessionButton.Visible = True

                    EnableControls(True)
                    Cursor.Current = Cursors.Default
                End If
            End If

            Application.DoEvents()
        End If
    End Sub

#End Region

    '*********************************************************************

#Region "=== Close Session ==="

    Private Sub CloseSessionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles CloseSessionButton.Click

        OpenSessionButton.Visible = True
        SessionConfigCombo.Visible = True
        CloseSessionButton.Visible = False

        PrinterID.Visible = False
        PrinterPrefs.Visible = False

        EnableControls(False)
        PrinterTabGetSetControls(False)

        Dim SDKReturn As SDK.Return = SDK.ID_CloseSession(hSession)
        If SDKReturn <> SDK.Return.Success Then
            HandleError("CloseSession", SDKReturn)
        End If
    End Sub

#End Region

    '*********************************************************************

#Region "=== Error Response ==="

    Dim errorresponsekp As New Dictionary(Of SDK.Response, String) From
    {
        {SDK.Response.OK, "OK"},
        {SDK.Response.Cancel, "Cancel"}
    }

    Private Sub InitErrorResponseCombo()
        ErrorResponseCombo.DataSource = New BindingSource(errorresponsekp, Nothing)
        ErrorResponseCombo.DisplayMember = "Value"
        ErrorResponseCombo.SelectedItem = SDK.Response.OK
    End Sub

    Private Sub ErrorResponseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles ErrorResponseButton.Click
        Dim response As SDK.Response = ErrorResponseCombo.SelectedItem.Key()
        Dim SDKReturn As SDK.Return = SDK.ID_ErrorResponse(hSession, response)

        If SDKReturn <> SDK.Return.Success Then
            HandleError("ErrorResponse", SDKReturn)
        End If
    End Sub

#End Region

    '*********************************************************************

#Region "=== Move Card ==="

    Dim movecardkp As New Dictionary(Of SDK.CardPosition, String) From
    {
        {SDK.CardPosition.TransferStandby, "TransferStandby"},
        {SDK.CardPosition.HeatedRoller, "HeatedRoller"},
        {SDK.CardPosition.FlipStandby, "FlipStandby"},
        {SDK.CardPosition.Rotate, "Rotate"},
        {SDK.CardPosition.MagEncoder, "MagEncoder"},
        {SDK.CardPosition.ContactEncoder, "ContactEncoder"},
        {SDK.CardPosition.Eject, "Eject"},
        {SDK.CardPosition.Reject, "Reject"},
        {SDK.CardPosition.Laminator, "Laminator"},
        {SDK.CardPosition.ContactlessEncoder, "ContactlessEncoder"}
    }

    Private Sub InitMoveCardCombo()
        MoveCardCombo.DataSource = New BindingSource(movecardkp, Nothing)
        MoveCardCombo.DisplayMember = "Value"
        MoveCardCombo.ValueMember = "Key"
    End Sub

    Private Sub MoveCardButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles MoveCardButton.Click
        Cursor.Current = Cursors.WaitCursor

        Dim position As SDK.CardPosition = MoveCardCombo.SelectedItem.Key
        Dim SDKReturn As SDK.Return = SDK.ID_MoveCard(hSession, position)
        If SDKReturn <> SDK.Return.Success Then
            HandleError("MoveCard", SDKReturn)
        Else
            WaitForPrinterToFinish()
        End If

        Cursor.Current = Cursors.Default
    End Sub

#End Region

    '*********************************************************************

#Region "=== Clean Printer ==="

    Private Sub CleanPrinterButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles CleanPrinterButton.Click
        Cursor.Current = Cursors.WaitCursor

        Dim SDKReturn As SDK.Return = SDK.ID_CleanPrinter(hSession)

        If SDKReturn <> SDK.Return.Success Then
            HandleError("CleanPrinter", SDKReturn)
        Else
            WaitForPrinterToFinish()
        End If

        Cursor.Current = Cursors.Default
    End Sub

#End Region

    '*********************************************************************

#Region "=== Restart Printer ==="

    Private Sub RestartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles RestartButton.Click
        Cursor.Current = Cursors.WaitCursor

        Dim SDKReturn As SDK.Return = SDK.ID_RestartPrinter(hSession)

        If SDKReturn <> SDK.Return.Success Then
            HandleError("RestartPrinter", SDKReturn)
        Else
            WaitForPrinterToFinish()
        End If

        Cursor.Current = Cursors.Default
    End Sub

#End Region

    '*********************************************************************

#Region "=== Print Test Card ==="

    Private Sub PrintTestButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles PrintTestCardButton.Click
        Cursor.Current = Cursors.WaitCursor

        Dim SDKReturn As SDK.Return = SDK.ID_PrintTestCard(hSession)

        If SDKReturn <> SDK.Return.Success Then
            HandleError("PrintTestCard", SDKReturn)
        Else
            WaitForPrinterToFinish()
        End If

        Cursor.Current = Cursors.Default
    End Sub

#End Region

    '*********************************************************************

#Region "=== Eject Mode ==="

    Dim ejectmodekp As New Dictionary(Of SDK.EjectMode, String) From
    {
        {SDK.EjectMode.On, "On"},
        {SDK.EjectMode.Off, "Off"}
    }

    Private Sub InitEjectModeCombo()
        EjectModeCombo.DataSource = New BindingSource(ejectmodekp, Nothing)
        EjectModeCombo.DisplayMember = "Value"
        EjectModeCombo.ValueMember = "Key"
    End Sub

    Private Sub EjectModeToMsgBox(ByVal Action As SDK.Action, ByVal mode As SDK.EjectMode)
        Dim sep As String = Separator(Action)
        PrinterMsgBox.AppendText("Eject Mode" + sep + ejectmodekp.Item(mode) + Environment.NewLine)
        PrinterMsgBox.AppendText(Environment.NewLine)
    End Sub

    Private Sub SetEjectModeCombo(ByVal mode As SDK.EjectMode)
        EjectModeCombo.Text = ejectmodekp.Item(mode)
    End Sub

    Private Function GetEjectMode(ByRef mode As SDK.EjectMode) As SDK.Return
        Dim SDKReturn As SDK.Return = SDK.ID_EjectMode(hSession, SDK.Action.Read, mode)
        If SDKReturn <> SDK.Return.Success Then
            HandleError("GetEjectMode", SDKReturn)
        End If
        Return SDKReturn
    End Function

    Private Sub EjectModeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles EjectModeButton.Click
        Dim mode As SDK.EjectMode = EjectModeCombo.SelectedItem.Key()

        If PrinterActionIsGet() Then
            If GetEjectMode(mode) = SDK.Return.Success Then
                SetEjectModeCombo(mode)
                EjectModeToMsgBox(SDK.Action.Read, mode)
            End If
        Else
            Dim SDKReturn As SDK.Return = SDK.ID_EjectMode(hSession, SDK.Action.Write, mode)
            If SDKReturn <> SDK.Return.Success Then
                HandleError("SetEjectMode", SDKReturn)
            Else
                EjectModeToMsgBox(SDK.Action.Write, mode)
            End If
        End If
    End Sub

#End Region

    '*********************************************************************

#Region "=== IP Settings ==="

    Dim ipaddresskp As New Dictionary(Of SDK.IPMode, String) From
    {
        {SDK.IPMode.Dynamic, "Dynamic"},
        {SDK.IPMode.Static, "Static"}
    }

    Private Sub InitIPModeCombo()
        IPModeCombo.DataSource = New BindingSource(ipaddresskp, Nothing)
        IPModeCombo.DisplayMember = "Value"
        IPModeCombo.ValueMember = "Key"
    End Sub

    Private Function IntToIPAddressString(ByVal value As Integer) As String
        Dim temp As VariantType = IPAddress.HostToNetworkOrder(value)
        Return New IPAddress(BitConverter.GetBytes(temp)).ToString()
    End Function

    Private Function IPAddressStringToInt(ByVal IPAddr As String) As Integer
        Return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(IPAddr).GetAddressBytes(), 0))
    End Function

    Private Sub IPDataToMsgBox(ByVal Action As SDK.Action, ByVal settings As SDK.IPData)
        Dim sep As String = Separator(Action)
        PrinterMsgBox.AppendText("Address Mode" + sep + ipaddresskp.Item(settings.Mode) + Environment.NewLine)
        PrinterMsgBox.AppendText("IP Address" + sep + IntToIPAddressString(settings.Address) + Environment.NewLine)
        PrinterMsgBox.AppendText("Subnet Mask" + sep + IntToIPAddressString(settings.Subnet) + Environment.NewLine)
        PrinterMsgBox.AppendText("Gateway" + sep + IntToIPAddressString(settings.Gateway) + Environment.NewLine)
        PrinterMsgBox.AppendText(Environment.NewLine)
    End Sub

    Private Function GetIPSettings(ByRef settings As SDK.IPData) As SDK.Return
        Dim SDKReturn As SDK.Return = SDK.ID_IPSettings(hSession, SDK.Action.Read, settings)
        If SDKReturn <> SDK.Return.Success Then
            HandleError("GetIPSettings", SDKReturn)
        Else
            IPModeCombo.Text = ipaddresskp.Item(settings.Mode)
            IPAddressBox.Text = IntToIPAddressString(settings.Address)
            IPSubnetBox.Text = IntToIPAddressString(settings.Subnet)
            IPGatewayBox.Text = IntToIPAddressString(settings.Gateway)
        End If

        Return SDKReturn
    End Function

    Private Sub IPSettingsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                Handles IPSettingsButton.Click
        Dim ipdata As New SDK.IPData

        Cursor.Current = Cursors.WaitCursor

        If PrinterActionIsGet() Then
            If GetIPSettings(ipdata) = SDK.Return.Success Then
                IPDataToMsgBox(SDK.Action.Read, ipdata)
            End If
        Else
            GetIPSettings(ipdata) 'Get MAC address for Ultima IP Update
            ipdata.Mode = IPModeCombo.SelectedItem.Key
            ipdata.Address = IPAddressStringToInt(IPAddressBox.Text)
            ipdata.Subnet = IPAddressStringToInt(IPSubnetBox.Text)
            ipdata.Gateway = IPAddressStringToInt(IPGatewayBox.Text)

            Dim SDKReturn As SDK.Return = SDK.ID_IPSettings(hSession, SDK.Action.Write, ipdata)
            If SDKReturn <> SDK.Return.Success Then
                HandleError("SetEraseSpeed", SDKReturn)
            Else
                IPDataToMsgBox(SDK.Action.Write, ipdata)
            End If
        End If

        Cursor.Current = Cursors.Default
    End Sub

#End Region

End Class
