Imports DigitalData.Modules.ZooFlow
Imports DigitalData.Modules.Logging
Imports DigitalData.GUIs.Common.Base
Imports DigitalData.Modules.ZooFlow.Constants
Imports DigitalData.Modules.EDMI.API
Imports DevExpress.XtraEditors
Imports System.Drawing
Imports DigitalData.Modules.EDMI.API.EDMIServiceReference
Imports DevExpress.Utils.Svg
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Grid.ViewInfo
Imports System.Windows.Forms

Public Class frmWorkflow_Adhoc_start
    Private ReadOnly Property LogConfig As LogConfig
    Private ReadOnly Property Logger As Logger
    Private Property OperationMode As OperationMode
    Private ReadOnly Environment As Environment
    Private ReadOnly AdHocWorkflow As AdHocWorkflow
    Private Client As Client
    Private IsLoading As Boolean = True
    Private WFUserList As List(Of User2Workflow)
    Private WorkflowList As List(Of Workflows)
    Private GridCursorLocation As Point
    Private oSelectedProfilID As Integer
    Private Property FormHelper As FormHelper
    Public Sub New(pLogConfig As LogConfig, pEnvironment As Environment, pAdhocWorkflow As AdHocWorkflow)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        Environment = pEnvironment
        AdHocWorkflow = pAdhocWorkflow
        LogConfig = pLogConfig
        Logger = pLogConfig.GetLogger()
    End Sub
    Private Function GetOperationMode() As OperationMode
        Dim oOperationMode As OperationMode

        If Environment.Service.Client.IsOnline AndAlso Environment.Service.Address <> String.Empty Then
            oOperationMode = OperationMode.WithAppServer
        Else
            oOperationMode = OperationMode.NoAppServer
        End If

        Return oOperationMode
    End Function

    Private Sub frmWorkflow_Adhoc_start_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            ' Operation mode is either guessed from service settings
            ' or explictly set from OperationModeOverride in Params
            OperationMode = GetOperationMode()
            Client = Environment.Service.Client

            WFUserList = New List(Of User2Workflow)
            WorkflowList = New List(Of Workflows)
            ' Initialize Viewer with GDPicture.NET License
            ' Hide options relating to a filepath for zooflow
            If OperationMode = OperationMode.ZooFlow Then
                '                RibbonPageGroupFilesystem.Visible = False
            End If

            If OperationMode = OperationMode.NoAppServer Then
                '               RibbonPageGroupCheckInOut.Visible = False
                '              RibbonPageGroupWorkflow.Visible = False
                '             RibbonPageGroupAttribute.Visible = False
            Else
                '            RibbonPageGroupFilesystem.Visible = False
            End If
            Dim oDatatableUserselect As DataTable
            Dim oDatatableWFSelect As DataTable
            Dim oSQL = AdHocWorkflow.AHWF_CMD_USR_SELECT
            Dim oResult As GetDatatableResponse = Nothing
            If OperationMode = OperationMode.ZooFlow Or OperationMode = OperationMode.WithAppServer Then
                oResult = Client.GetDatatableFromECM(oSQL)
                If oResult.OK = False Then
                    Throw New ApplicationException(oResult.ErrorMessage)
                Else
                    oDatatableUserselect = oResult.Table
                End If

            Else
                oDatatableUserselect = Environment.Database.GetDatatable(oSQL)
            End If
            If Not IsNothing(oDatatableUserselect) Then
                LookUpEdit1.Properties.DataSource = oDatatableUserselect
                LookUpEdit1.Properties.ValueMember = oDatatableUserselect.Columns(0).ColumnName
                LookUpEdit1.Properties.DisplayMember = oDatatableUserselect.Columns(1).ColumnName

            End If
            oSQL = AdHocWorkflow.AHWF_CMD_LAYOUT_SELECT
            If OperationMode = OperationMode.ZooFlow Or OperationMode = OperationMode.WithAppServer Then
                oResult = Client.GetDatatableFromECM(oSQL)
                If oResult.OK = False Then
                    Throw New ApplicationException(oResult.ErrorMessage)
                Else
                    oDatatableWFSelect = oResult.Table
                End If

            Else
                oDatatableWFSelect = Environment.Database.GetDatatable(oSQL)
            End If
            If Not IsNothing(oDatatableWFSelect) Then
                For Each oRow As DataRow In oDatatableWFSelect.Rows
                    WorkflowList.Add(New Workflows() With {
               .ID = oRow.Item(0),
               .Description = IIf(IsDBNull(oRow.Item(2)), "", oRow.Item(2)),
               .Title = oRow.Item(1),
               .Image = SvgImageCollection1.Item("Workflow")
                           })
                Next
            End If
            GridControlWorkflows.DataSource = WorkflowList

            TileViewWorkflows.FocusedRowHandle = GridControl.InvalidRowHandle

            If OperationMode = OperationMode.NoAppServer Then
                ' panelContainerStatus.Visibility = Docking.DockVisibility.Hidden
            End If
            WFUserList = New List(Of User2Workflow)
            ' Hide the complete Navigation Ribbon Group if desired

        Catch ex As Exception
            Logger.Error(ex)
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Error while loading form:")


        Finally
            IsLoading = False

        End Try
    End Sub

    Private Sub SimpleButton1_Click(sender As Object, e As EventArgs)

    End Sub


    Friend Class User2Workflow
        Public Property UserID As Integer
        Public Property EMail As String
        Public Property FullName As String
        Public Property Image As SvgImage
        Public Property Count As Integer = 0

        Public ReadOnly Property DisplayName As String
            Get
                Return UserID
            End Get
        End Property

    End Class
    Friend Class Workflows
        Public Property Description As String
        Public Property Title As String
        Public Property ID As Integer
        Public Property Image As SvgImage
        Public Property Count As Integer = 0

        Public ReadOnly Property DisplayName As String
            Get
                Return ID
            End Get
        End Property

    End Class

    Private Sub LookUpEdit1_EditValueChanged(sender As Object, e As EventArgs) Handles LookUpEdit1.EditValueChanged
        Dim editor As DevExpress.XtraEditors.LookUpEdit = CType(sender, DevExpress.XtraEditors.LookUpEdit)
        Dim row As DataRowView = CType(editor.Properties.GetDataSourceRowByKeyValue(editor.EditValue), DataRowView)
        Dim UsID As Object = row("ID")
        Dim UsFname As Object = row("FullName")
        Dim UsEmail As Object = row("Email")
        WFUserList.Add(New User2Workflow() With {
               .UserID = UsID,
               .FullName = UsFname,
               .EMail = UsEmail,
               .Image = SvgImageCollection1.Item("actions_user")
                           })

        GridSelectedUsers.DataSource = Nothing
        GridSelectedUsers.DataSource = WFUserList

        TileViewUser.FocusedRowHandle = GridControl.InvalidRowHandle


    End Sub

    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        Dim oUserRow = TileViewUser.GetRow(TileViewUser.FocusedRowHandle)
        If oUserRow IsNot Nothing AndAlso TypeOf oUserRow Is User2Workflow Then
            Dim oDateSearch As User2Workflow = oUserRow

            WFUserList.Remove(oDateSearch)
            GridSelectedUsers.DataSource = Nothing
            GridSelectedUsers.DataSource = WFUserList
        End If

    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        Try
            Dim oErrorOcurred As Boolean = False

            If oSelectedProfilID = 0 Then
                BarStaticItem1.Caption = "Please choose a workflow via clickin on it..."
                BarStaticItem1.ItemAppearance.Normal.BackColor = Color.Orange
                Exit Sub
            End If
            Dim oInsert = $"DECLARE @OUT_ID 
                            BIGINT EXEC PRPM_AH_WF_ADD_OBJ_REL  {AdHocWorkflow.OBJECT_ID}, {oSelectedProfilID}, '{txtWORK_INSTRUCTION.Text}','{Environment.User.UserName}',@OUT_ID OUTPUT
                            SELECT @OUT_ID"
            Dim oAdhocWF_ID
            If OperationMode = OperationMode.ZooFlow Or OperationMode = OperationMode.WithAppServer Then
                Dim oResponse = Client.GetScalarValueFromECM(oInsert)
                If oResponse.OK Then
                    oAdhocWF_ID = oResponse.Scalar
                Else
                    MsgBox("Unexpected error in WF-Party-Creator. Check your log and inform Admin-Team", MsgBoxStyle.Critical)
                    oErrorOcurred = True
                    Exit Sub
                End If
            Else
                oAdhocWF_ID = Environment.Database.GetScalarValue(oInsert)
            End If

            If Not IsNothing(oAdhocWF_ID) Then
                For index = 0 To TileViewUser.RowCount
                    Dim oRow As User2Workflow = TileViewUser.GetRow(index)

                    If oRow Is Nothing Then
                        Continue For
                    End If

                    oInsert = $"DECLARE @OUT_ID 
                            BIGINT EXEC PRPM_AH_WF_PARTY  {oAdhocWF_ID}, {oRow.UserID}, '{Environment.User.UserName}',@OUT_ID OUTPUT
                            SELECT @OUT_ID"
                    Dim oID
                    If OperationMode = OperationMode.ZooFlow Or OperationMode = OperationMode.WithAppServer Then
                        Dim oResponse = Client.GetScalarValueFromECM(oInsert)
                        If oResponse.OK Then
                            oID = oResponse.Scalar
                        Else
                            MsgBox("Unexpected error in WF-Party-Creator. Check your log and inform Admin-Team", MsgBoxStyle.Critical)
                            oErrorOcurred = True
                            Exit For
                        End If
                    Else
                        oID = Environment.Database.GetScalarValue(oInsert)
                    End If
                Next
            End If
            If oErrorOcurred = False Then
                Me.Close()
            End If
        Catch ex As Exception
            Logger.Error(ex)
            BarStaticItem1.Caption = ex.Message
            BarStaticItem1.ItemAppearance.Normal.BackColor = Color.Red
            FormHelper.ShowErrorMessage(ex, "Error in AHWF Save and Close")
        End Try


    End Sub


    Private Sub TileViewWorkflows_MouseDown(sender As Object, e As MouseEventArgs) Handles TileViewWorkflows.MouseDown
        GridCursorLocation = e.Location
    End Sub

    Private Sub TileViewWorkflows_ItemClick(sender As Object, e As Views.Tile.TileViewItemClickEventArgs) Handles TileViewWorkflows.ItemClick
        Try
            Dim oWorkflowID As Workflows = TileViewWorkflows.GetRow(TileViewWorkflows.FocusedRowHandle)
            Try
                If CInt(oWorkflowID.ID) > 0 Then
                    oSelectedProfilID = oWorkflowID.ID
                End If
            Catch ex As Exception
                oSelectedProfilID = 0
            End Try
        Catch ex As Exception
            oSelectedProfilID = 0
        End Try


    End Sub
End Class