Imports DevExpress.XtraEditors
Imports DevExpress.XtraSplashScreen
Imports DigitalData.GUIs.Common
Imports DigitalData.GUIs.ZooFlow.ClassConstants
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.ZooFlow

Public Class frmFlowSearch1
    Private _Environment As Environment
    Private Logger As Logger

    Private TOGGLE_Change As Boolean = False
    Private LIMITATION_DATE As Boolean = False
    Private SEARCH_FACT_DATE_ATTRIBUTE = "ADDED_WHEN"
    Private SEARCH_FACT_DATE As String = "MONTH(OBJ.ADDED_WHEN) <> 13"
    Private CONST_CR_TODAY As String = "CREATED_TODAY"
    Private CONST_CR_YDAY As String = "CREATED_YESTERDAY"
    Private CONST_CR_L7DAYS As String = "CREATED_LAST7DAYS"
    Private CONST_CR_Y_CURR As String = "CREATED_YEAR_CURRENT"
    Private CONST_CR_Y_LAST As String = "CREATED_YEAR_LAST"
    Private CONST_CR_M_CURR As String = "CREATED_MONTH_CURRENT"
    Private CONST_CR_M_LAST As String = "CREATED_MONTH_LAST"

    Private CONST_DATE_TOMORROW As String = "TOMORROW"
    Private SEARCH_PARAM3

    Private ExplizitDate As Boolean = False

    Dim oBASESEARCH As String
    Sub ResetTogglesDate()
        TOGGLE_Change = True
        ToggleSwitchToday.IsOn = False
        ToggleSwitchYesterday.IsOn = False
        ToggleSwitchTomorrow.IsOn = False
        ToggleSwitchLastWeek.IsOn = False
        ToggleSwitchYear_Last.IsOn = False
        ToggleSwitchYear.IsOn = False
        ToggleSwitchMonth.IsOn = False
        ToggleSwitchMonth_Last.IsOn = False
        TOGGLE_Change = False
    End Sub

    Private Sub ToggleSwitchToday_Toggled(sender As Object, e As EventArgs) Handles _
        ToggleSwitchToday.Toggled,
        ToggleSwitchYesterday.Toggled,
        ToggleSwitchYear.Toggled,
        ToggleSwitchYear_Last.Toggled,
        ToggleSwitchMonth_Last.Toggled,
        ToggleSwitchMonth.Toggled,
        ToggleSwitchLastWeek.Toggled,
        ToggleSwitchTomorrow.Toggled

        If TOGGLE_Change = True Then
            Exit Sub
        End If

        Dim oToggle As ToggleSwitch = TryCast(sender, ToggleSwitch)

        If oToggle.IsOn Then
            TOGGLE_Change = True
            Dim oWHENDATE As String
            Select Case oToggle.Name
                Case "ToggleSwitchTomorrow"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("YEAR(@ATTRIBUTE) = YEAR(GETDATE())", CONST_DATE_TOMORROW)
                Case "ToggleSwitchYear"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("YEAR(@ATTRIBUTE) = YEAR(GETDATE())", CONST_CR_Y_CURR)
                Case "ToggleSwitchYear_Last"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("YEAR(@ATTRIBUTE) = YEAR(GETDATE())", CONST_CR_TODAY)

                Case "ToggleSwitchMonth"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("MONTH(@ATTRIBUTE) = MONTH(GETDATE())", CONST_CR_M_CURR)
                Case "ToggleSwitchMonth_Last"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    Dim currentDate As DateTime = DateTime.Now
                    If currentDate.Month = 1 Then
                        oWHENDATE = GET_DATE_LIMITATION("MONTH(@ATTRIBUTE) = 12 " & vbNewLine & "AND YEAR(@ATTRIBUTE) = (YEAR(GETDATE()) -1)", CONST_CR_M_LAST)
                    Else
                        oWHENDATE = GET_DATE_LIMITATION("MONTH(@ATTRIBUTE) = (MONTH(GETDATE()) -1)", CONST_CR_M_LAST)
                    End If
                Case "ToggleSwitchToday"
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("convert(DATE,@ATTRIBUTE) = convert(DATE,GETDATE())", CONST_CR_TODAY)
                Case "ToggleSwitchYesterday"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchLastWeek.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("convert(DATE,@ATTRIBUTE) = convert(DATE,GETDATE()-1)", CONST_CR_YDAY)
                Case "ToggleSwitchLastWeek"
                    ToggleSwitchToday.IsOn = False
                    ToggleSwitchTomorrow.IsOn = False
                    ToggleSwitchYesterday.IsOn = False
                    ToggleSwitchYear.IsOn = False
                    ToggleSwitchYear_Last.IsOn = False
                    ToggleSwitchMonth.IsOn = False
                    ToggleSwitchMonth_Last.IsOn = False
                    oWHENDATE = GET_DATE_LIMITATION("convert(DATE,@ATTRIBUTE) = convert(DATE,GETDATE()-1)", CONST_CR_L7DAYS)
            End Select
            SEARCH_FACT_DATE = oWHENDATE
            TOGGLE_Change = False
            LIMITATION_DATE = True
        Else
            If ToggleSwitchToday.IsOn = False And ToggleSwitchYesterday.IsOn = False And ToggleSwitchYear.IsOn = False And ToggleSwitchYear_Last.IsOn = False And
                ToggleSwitchMonth_Last.IsOn = False And ToggleSwitchMonth.IsOn = False And ToggleSwitchLastWeek.IsOn = False And ToggleSwitchTomorrow.IsOn = False Then

                LIMITATION_DATE = False
                SEARCH_PARAM3 = ""
            End If
        End If
    End Sub
    Private Function GET_DATE_LIMITATION(pInput As String, pVariant As String) As String
        Try
            If SEARCH_FACT_DATE_ATTRIBUTE = "ADDED_WHEN" Then
                SEARCH_PARAM3 = "ECM_" & pVariant
                Return pInput.Replace("@ATTRIBUTE", "OBJ.ADDED_WHEN")

            Else
                Dim oSTR = $"GRPDATE.[{SEARCH_FACT_DATE_ATTRIBUTE}]"
                Return pInput.Replace("@ATTRIBUTE", oSTR)
            End If
        Catch ex As Exception
            Return pInput
            Logger.Error(ex)
        End Try
    End Function

    Private Sub cmbLimitationDateAttr_SelectedValueChanged(sender As Object, e As EventArgs) Handles cmbLimitationDateAttr.SelectedValueChanged
        If cmbLimitationDateAttr.SelectedIndex <> -1 Then
            Try

                Dim oEditValue As String = cmbLimitationDateAttr.SelectedItem.ToString

                If oEditValue = IDB_ADDED_WHEN_String_German Or oEditValue = IDB_ADDED_WHEN_String_Englisch Then
                    SEARCH_FACT_DATE_ATTRIBUTE = "ADDED_WHEN"
                Else
                    SEARCH_FACT_DATE_ATTRIBUTE = oEditValue
                    SEARCH_FACT_DATE = $"MONTH(GRPDATE.[{SEARCH_FACT_DATE_ATTRIBUTE}]) <> 13"
                End If
                'SearchContent()
            Catch ex As Exception
                Logger.Error(ex)
            End Try
        End If
    End Sub

    Private Sub frmFlowSearch1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Logger = My.LogConfig.GetLogger()

        Try
            If My.Application.User.Language = "de-DE" Then
                cmbLimitationDateAttr.Items.Add(IDB_ADDED_WHEN_String_German)
            Else
                cmbLimitationDateAttr.Items.Add(IDB_ADDED_WHEN_String_Englisch)
            End If
            'Dim oDT As DataTable = My.DatabaseIDB.GetDatatable($"SELECT * FROM VWIDB_BE_ATTRIBUTE WHERE TYPE_ID IN (5,6) AND LANG_ID = {My.Application.User.LanguageId}")

            For Each oRow As DataRow In My.Tables.DTIDB_ATTRIBUTE.Rows
                If CBool(oRow.Item("SYS_ATTRIBUTE")) = False And (oRow.Item("TYP_ID") = 5 Or oRow.Item("TYP_ID") = 6) Then
                    cmbLimitationDateAttr.Items.Add(oRow.Item("ATTR_TITLE"))
                End If

            Next
            _Environment = My.Application.GetEnvironment
            'Dim editor As BarEditItem = BarEditItemDate
            ' editor = TryCast(BarEditItemDate, ComboBoxEdit)
            If My.Application.User.Language = "de-DE" Then
                cmbLimitationDateAttr.SelectedIndex = 0
                '    BarEditItemDate.EditValue = "Erstellt Wann"
            Else
                cmbLimitationDateAttr.SelectedIndex = 1
                '    BarEditItemDate.EditValue = "Added When"
            End If

            For Each oRow As DataRow In My.Tables.DTIDB_COMMON_SQL.Rows
                If oRow.Item("TITLE") = SQLCMD_FLOW_SEARCH_BASE Then
                    oBASESEARCH = oRow.Item("SQL_COMMAND")
                    oBASESEARCH = oBASESEARCH.Replace("@USER_ID", My.Application.User.UserId)
                    oBASESEARCH = oBASESEARCH.Replace("@LANG_CODE", My.Application.User.Language)
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
            Logger.Error(ex)
        End Try
        Me.BringToFront()


    End Sub

    Private Async Function BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) As Threading.Tasks.Task Handles BarButtonItem1.ItemClick
        Dim oHandle = SplashScreenManager.ShowOverlayForm(Me)

        Try
            Await Search_GO()
        Catch ex As Exception
            Logger.Error(ex)
        Finally
            SplashScreenManager.CloseOverlayForm(oHandle)
        End Try
    End Function
    Private Async Function Search_GO() As Threading.Tasks.Task
        Dim oWindowTitle
        Dim oSearchTerm = txtSearchInput.Text

        Dim oParams = New DocumentResultList.Params() With {
           .WindowGuid = "FlowSearch",
           .WindowTitle = GetResultWindowString(oSearchTerm),
           .OperationModeOverride = Modules.ZooFlow.Constants.OperationMode.ZooFlow,
           .ProfileGuid = 354522
        }

        Dim oP3 = $"{SEARCH_FACT_DATE_ATTRIBUTE}~{SEARCH_PARAM3}"
        If ExplizitDate Then
            Dim oDate2 As Date
            If Not IsNothing(DateEditTill.EditValue) Then
                oDate2 = CDate(DateEditTill.EditValue)
            Else
                oDate2 = CDate(DateEditFrom.EditValue)
            End If
            Dim oProc = $"EXEC PRIDB_SEARCH_ADD_USR_DATE {My.Application.User.UserId},'{CDate(DateEditFrom.EditValue)}','{oDate2}'"
            If Await My.Database.ExecuteNonQueryIDBAsync(oProc) = True Then
                oP3 = $"{SEARCH_FACT_DATE_ATTRIBUTE}~DATEPART"
            End If
        End If

        Dim oSQL = $"EXEC PRIDB_SEARCH_TEXT_GET_RESULTS {My.Application.User.UserId},'{oSearchTerm}','{oP3}'"

        If Await My.Database.ExecuteNonQueryIDBAsync(oSQL) = True Then
            Dim oDTDocResult = Await My.Database.GetDatatableIDBAsync(oBASESEARCH)
            If oDTDocResult.Rows.Count > 0 Then
                oParams.Results.Add(New DocumentResultList.DocumentResult() With {
                    .Title = "FlowSearchXYZ",
                    .Datatable = oDTDocResult
                })
                Dim oForm As New frmDocumentResultList(My.LogConfig, _Environment, oParams)

                AddHandler oForm.NeedsRefresh, AddressOf Form_NeedsRefresh

                oForm.Show()
            Else
                bsiStatus.Caption = "No Results"
            End If
        Else
            bsiStatus.Caption = "Error in FlowSearch - Check Your log"
        End If
    End Function

    Private Sub Form_NeedsRefresh(sender As Object, e As Integer)

    End Sub

    Private Async Function txtSearchInput_KeyUp(sender As Object, e As KeyEventArgs) As Threading.Tasks.Task Handles txtSearchInput.KeyUp
        If e.KeyCode = Keys.Return Then
            If txtSearchInput.Text = String.Empty Then
                Return
            End If

            Dim oHandle = SplashScreenManager.ShowOverlayForm(Me)

            Try
                Await Search_GO()
            Catch ex As Exception
                Logger.Error(ex)
            Finally
                SplashScreenManager.CloseOverlayForm(oHandle)
            End Try
        End If
    End Function
    Private Function GetResultWindowString(SearchContent As String) As String
        If SearchContent <> String.Empty Then
            If My.Application.User.Language = State.UserState.LANG_DE_DE Then

                Return $"Suche Nach '{txtSearchInput.Text}'"
            Else
                Return $"Search For '{txtSearchInput.Text}'"
            End If
        Else
            If My.Application.User.Language = State.UserState.LANG_DE_DE Then
                Return $"Suche Datumsbegrenzt"
            Else
                Return $"Search via date"
            End If
        End If


    End Function

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        txtSearchInput.Text = ""
        ResetTogglesDate()
        ToggleSwitchDateto.IsOn = False
        ExplizitDate = False
    End Sub

    Private Sub ToggleSwitch1_Toggled(sender As Object, e As EventArgs) Handles ToggleSwitchDateto.Toggled
        Dim oToggle As ToggleSwitch = TryCast(sender, ToggleSwitch)

        If oToggle.IsOn Then
            DateEditTill.Enabled = True
            lblDatefrom.Text = "Datum von"
        Else
            DateEditTill.Enabled = False
            lblDatefrom.Text = "Datum"
        End If
    End Sub

    Private Sub DateEdit1_DateTimeChanged(sender As Object, e As EventArgs) Handles DateEditFrom.DateTimeChanged
        Dim oobj = DateEditFrom.EditValue
        If Not IsNothing(oobj) Then
            ResetTogglesDate()
        End If

    End Sub

    Private Sub DateEdit1_EditValueChanged(sender As Object, e As EventArgs) Handles DateEditFrom.EditValueChanged
        Dim oobj = DateEditFrom.EditValue
        If Not IsNothing(oobj) Then
            ExplizitDate = True
        End If

    End Sub
End Class