Imports DevExpress.Utils
Imports DevExpress.XtraBars
Imports DevExpress.XtraBars.Ribbon
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Filesystem
Imports DigitalData.Modules.Language

Namespace DocumentResultList
    Public Class Workspace(Of TConfig)
        Inherits BaseClass

        Private ReadOnly Manager As WorkspaceManager
        Private ReadOnly Config As ConfigManager(Of TConfig)
        Private ReadOnly FileEx As File

        Public Const WORKSPACE_FILENAME As String = "Workspaces.xml"
        Public Const WORKSPACE_DIRECTORY As String = "Workspaces"
        Public Const DEFAULT_WORKSPACE As String = "Default"

        Private _CurrentWorkspace As String = Nothing

        Public Event WorkspaceLoaded As EventHandler(Of String)

        Public ReadOnly Property CurrentWorkspace As String
            Get
                Return _CurrentWorkspace
            End Get
        End Property

        Public ReadOnly Property Workspaces As List(Of String)
            Get
                Return Manager.Workspaces.
                    Select(Function(ws As IWorkspace) ws.Name).
                    ToList()
            End Get
        End Property

        Public Sub New(pLogConfig As LogConfig, pConfigManager As ConfigManager(Of TConfig), pWorkspaceManager As WorkspaceManager)
            MyBase.New(pLogConfig)
            Manager = pWorkspaceManager
            Config = pConfigManager
            FileEx = New File(pLogConfig)
        End Sub

        Private Function GetWorkspaceDirectoryPath() As String
            Dim oConfigPath As String = Config.UserConfigPath
            Dim oConfigDirectory As String = IO.Path.Combine(IO.Path.GetDirectoryName(oConfigPath), WORKSPACE_DIRECTORY)

            If IO.Directory.Exists(oConfigDirectory) = False Then
                Try
                    IO.Directory.CreateDirectory(oConfigDirectory)
                Catch ex As Exception
                    Logger.Error(ex)
                End Try
            End If

            Return oConfigDirectory
        End Function

        Private Function GetWorkspacePath(pWorkspaceName As String) As String
            Dim oDirectory = GetWorkspaceDirectoryPath()
            Dim oFilename As String = Utils.ConvertTextToSlug(pWorkspaceName) & ".xml"
            Return IO.Path.Combine(oDirectory, oFilename)
        End Function

        Public Function SaveWorkspaces() As Boolean
            Try
                If Manager.Workspaces.Count = 0 Then
                    Logger.Debug("No Workspace exists yet, capturing Workspace [{0}]", DEFAULT_WORKSPACE)
                    Manager.CaptureWorkspace(DEFAULT_WORKSPACE)
                    _CurrentWorkspace = DEFAULT_WORKSPACE
                End If

                SaveWorkspace(_CurrentWorkspace)

                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        End Function

        Public Function SaveWorkspace(pName As String, Optional pForce As Boolean = False)
            Try
                Dim oFilePath = GetWorkspacePath(pName)
                Logger.Debug("Saving Workspace [{0}] to [{1}]", pName, oFilePath)
                Manager.CaptureWorkspace(pName)
                Manager.SaveWorkspace(pName, oFilePath, createIfNotExisting:=pForce)
                Return True

            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        End Function

        Public Function ResetWorkspaces() As Boolean
            Try
                Dim oFilePath = GetWorkspaceDirectoryPath()

                If IO.Directory.Exists(oFilePath) = False Then
                    Logger.Debug("Workspaces directory not found, no workspaces will be deleted!")
                    Return True
                End If

                Dim oFiles = IO.Directory.GetFiles(oFilePath)

                If oFiles.Count = 0 Then
                    Logger.Debug("No Workspaces found, no workspaces will be deleted!")
                    Return True
                End If

                For Each oFile In oFiles
                    Try
                        IO.File.Delete(oFile)
                    Catch ex As Exception
                        Logger.Error(ex)
                    End Try
                Next

                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        End Function

        Public Function ResetWorkspace(pName As String) As Boolean
            Try
                Dim oFilePath = GetWorkspacePath(pName)
                Manager.RemoveWorkspace(pName)

                If IO.File.Exists(oFilePath) = False Then
                    Logger.Debug("Workspace does not exist!")
                    Return True
                End If

                IO.File.Delete(oFilePath)

                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        End Function

        Public Function LoadWorkspaces() As Boolean
            Try
                Dim oFilePath = GetWorkspaceDirectoryPath()

                If IO.Directory.Exists(oFilePath) = False Then
                    Logger.Warn("Workspaces directory not found, workspaces will not be saved!")
                    Return True
                End If

                Dim oFiles = IO.Directory.GetFiles(oFilePath)

                If oFiles.Count = 0 Then
                    Logger.Debug("Workspaces empty, creating default workspace")
                    Manager.CaptureWorkspace(DEFAULT_WORKSPACE)
                    _CurrentWorkspace = DEFAULT_WORKSPACE
                End If

                For Each oFile In oFiles
                    Dim oWorkspaceName As String = IO.Path.GetFileNameWithoutExtension(oFile)
                    Manager.LoadWorkspace(oWorkspaceName, oFile, True)
                    Logger.Debug("Workspace [{0}] loaded!", oWorkspaceName)
                Next

                Return True
            Catch ex As Exception
                Logger.Error(ex)
                Return False
            End Try
        End Function

        Public Sub LoadWorkspace(pName As String)
            Try
                Manager.AllowTransitionAnimation = DefaultBoolean.False
                Manager.ApplyWorkspace(pName)
                _CurrentWorkspace = pName
                RaiseEvent WorkspaceLoaded(Me, pName)

                Manager.AllowTransitionAnimation = DefaultBoolean.True
            Catch ex As Exception
                Logger.Error(ex)
            End Try
        End Sub

        Public Function GetWorkspaceButtons(pRibbonControl As RibbonControl, pRibbonGroup As RibbonPageGroup) As Boolean
            Dim oItems As New List(Of BarItem)

            For Each oWorkspace In Manager.Workspaces
                Dim oItem As BarButtonItem = pRibbonControl.Items.CreateButton(oWorkspace.Name)
                oItem.ImageIndex = 1
                oItem.Id = pRibbonControl.Manager.GetNewItemId()
                oItem.Tag = oWorkspace

                AddHandler oItem.ItemClick, AddressOf Item_ItemClick

                oItems.Add(oItem)
            Next

            pRibbonGroup.ItemLinks.AddRange(oItems)

            Return True
        End Function

        Private Sub Item_ItemClick(sender As Object, e As ItemClickEventArgs)
            Dim oTag = e.Item.Tag

            If oTag IsNot Nothing AndAlso TypeOf oTag Is IWorkspace Then
                Dim oWorkspace As IWorkspace = oTag
                LoadWorkspace(oWorkspace.Name)
            End If
        End Sub
    End Class



End Namespace