Imports IntraSell_DLL

Public Class Bankomat
    Public Event BezahltMitBankomat(amount As Decimal)

    Dim _amount As Decimal

    Property Amount As Decimal
        Get
            Return _amount
        End Get
        Set(value As Decimal)
            _amount = value
        End Set
    End Property

    Property currency As String = "EUR"

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
    End Sub

    'UserControl overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()>
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            Unregister()
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    Public Shadows Sub Load() Handles MyBase.Load
        Try
            If amount <= 0 Then
                Return 'kein payment provider kann mit 0 zahlen
            End If
            If currency <> "EUR" Then
                Return 'nur EUR erlaubt
            End If
            If PaymentProviderRegistry.registeredProviders IsNot Nothing Then

                For Each prov In PaymentProviderRegistry.registeredProviders
                    Dim btn = prov.GetPaymentButton()
                    WriteLog("Lade PaymentProvider " & btn.Text)
                    prov.SetAmount(Amount, currency)

                    If Not TableLayoutPanel1.Controls.Contains(btn) Then
                        btn.Dock = DockStyle.Fill
                        btn.BackColor = Color.White
                        btn.Margin = New System.Windows.Forms.Padding(0, 0, 0, 0)
                        TableLayoutPanel1.Controls.Add(btn)


                        'Unregister all old registrations
                        RemoveHandler btn.Click, AddressOf PaymentStart
                        RemoveHandler prov.PurchaseOK, AddressOf PaymentOK
                        RemoveHandler prov.PurchaseFailed, AddressOf PurchaseFailed
                        RemoveHandler prov.PurchaseTimeout, AddressOf PurchaseTimeout

                        AddHandler btn.Click, AddressOf PaymentStart
                        AddHandler prov.PurchaseOK, AddressOf PaymentOK
                        AddHandler prov.PurchaseFailed, AddressOf PurchaseFailed
                        AddHandler prov.PurchaseTimeout, AddressOf PurchaseTimeout

                    End If

                    Dim buttonBalance = prov.GetBalanceButton()
                    If buttonBalance IsNot Nothing Then
                        If Not TableLayoutPanel1.Controls.Contains(buttonBalance) Then

                            buttonBalance.Text = "Bilanz drucken"
                            buttonBalance.Dock = DockStyle.Fill
                            buttonBalance.BackColor = Color.White

                            buttonBalance.Tag = prov
                            TableLayoutPanel1.Controls.Add(buttonBalance)

                            'Unregister all old registrations

                            RemoveHandler prov.BalanceFailed, AddressOf BalanceFailed
                            RemoveHandler prov.BalanceOK, AddressOf BalanceOK
                            'RemoveHandler buttonBalance.Click, AddressOf Balance

                            AddHandler prov.BalanceOK, AddressOf BalanceOK
                            AddHandler prov.BalanceFailed, AddressOf BalanceFailed
                            'AddHandler buttonBalance.Click, AddressOf Balance
                        End If
                    End If
                Next
            End If
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Public Sub Unregister() ' Handles MyBase.Disposed 
        Try
            If PaymentProviderRegistry.registeredProviders Is Nothing Then Exit Sub

            For Each prov In PaymentProviderRegistry.registeredProviders

                WriteLog("Unregister PaymentProvider " + prov.ToString)

                RemoveHandler prov.PurchaseOK, AddressOf PaymentOK
                RemoveHandler prov.PurchaseFailed, AddressOf PurchaseFailed
                RemoveHandler prov.PurchaseTimeout, AddressOf PurchaseTimeout

                Dim btn = prov.GetPaymentButton()
                WriteLog("Unload PaymentProvider " + btn.Text)

                btn.Parent = Nothing
                If TableLayoutPanel1.Controls.Contains(btn) Then
                    TableLayoutPanel1.Controls.Remove(btn)
                End If

                Dim btnBalance = prov.GetBalanceButton()
                If btnBalance IsNot Nothing Then
                    btnBalance.Parent = Nothing
                    If TableLayoutPanel1.Controls.Contains(btnBalance) Then
                        TableLayoutPanel1.Controls.Remove(btnBalance)
                    End If
                End If


                'Nicht DisposeProvider, weil sonst bei der neu Initialisierung nicht funktioniert,
                ' DisposeProvider wird beim Beenden des Plugins aufgerufen
                'If Not prov Is Nothing Then
                'prov.DisposeProvider()
                'End If

            Next
        Catch ex As Exception
            HandleAppError(ex, Silent:=True)
        End Try
    End Sub

    Private Sub PaymentStart(sender As Object, e As EventArgs)
        Try
            Cursor = Cursors.WaitCursor
            'PleaseWait.MdiParent = Main
            PleaseWait.ShowMessage("Bitte die Instruktionen am Terminal befolgen!")
            PleaseWait.StartPosition = FormStartPosition.CenterScreen
            PleaseWait.TopMost = True
            PleaseWait.Show()
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub buttonBezahlungBankomat_Click(sender As Object, e As EventArgs) Handles buttonBezahlungBankomat.Click
        If MsgBox("Bankomat Bestätigung erhalten?", vbYesNo, "Bankomat") = vbYes Then
            RaiseEvent BezahltMitBankomat(0)
        End If
    End Sub

    Private Sub PaymentOK(amount As Decimal)
        Try
            Me.Invoke(Sub()
                          RaiseEvent BezahltMitBankomat(amount)
                          Cursor = Cursors.Default
                          PleaseWait.BackColor = Color.Green
                          Dim msg = "Zahlung erfolgreich!"
                          PleaseWait.ShowMessage(msg)
                          ClosePlsWait()

                      End Sub)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Sub ClosePlsWait()
        Dim timer As New Timer
        timer.Interval = 3000
        AddHandler timer.Tick, AddressOf ClosePlsWait
        timer.Enabled = True
    End Sub

    Private Sub ClosePlsWait(sender As Object, e As EventArgs)
        Dim timer = CType(sender, Timer)
        timer.Dispose()
        PleaseWait.Close()
    End Sub

    Private Sub PurchaseFailed(reason As String)
        Try
            Me.Invoke(Sub()
                          PleaseWait.BackColor = Color.Red
                          Cursor = Cursors.Default
                          Dim msg = "Zahlung fehlgeschlagen! Ursache :" & reason
                          PleaseWait.ShowMessage(msg)
                          WriteLog(msg)
                          'MsgBox(msg, vbCritical)
                          ClosePlsWait() 'PleaseWait.Close()
                      End Sub)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub PurchaseTimeout()
        Me.Invoke(Sub()
                      PleaseWait.BackColor = Color.Red
                      PleaseWait.ShowMessage("Zahlung wegen Timeout fehlgeschlagen!")
                      Cursor = Cursors.Default
                      Dim msg = "Zahlung wegen Timeout fehlgeschlagen!"
                      WriteLog(msg)
                      'MsgBox(msg, vbCritical)
                      ClosePlsWait() 'PleaseWait.Close()
                  End Sub)
    End Sub

    Private Sub Balance(sender As Object, e As EventArgs)
        Try
            Cursor = Cursors.WaitCursor
            Dim prov As InterfacePaymentProvider = CType(sender, Button).Tag
            prov.Balance()
        Catch ex As Exception
            HandleAppError(ex)
        Finally
            Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub BalanceOK(merchantReceipt As String)
        Try
            Cursor = Cursors.Default
            PleaseWait.Close()
            Dim filename As String = "MerchantReceipt_" & Format(Now, "yyyyddMM") & ".txt"
            IO.File.WriteAllText(filename, merchantReceipt)
            PrintFile(filename)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub BalanceFailed(reason As String)
        Try
            PleaseWait.Close()
            Cursor = Cursors.Default
            Dim msg = "Balance fehlgeschlagen! Ursache: " & reason
            WriteLog(msg)
            MsgBox(msg, vbCritical)
        Catch ex As Exception
            HandleAppError(ex)
        End Try
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        Unregister()
    End Sub

End Class
