Imports System.IO
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Patterns
Imports DigitalData.Modules.Language
Imports DigitalData.Services.EDMIService.Methods.Database
Imports DigitalData.Services.EDMIService.Methods.IDB
Imports DigitalData.Modules.ZooFlow.State
Imports DigitalData.Modules.Base.IDB

Namespace Methods.IDB.ImportFile
    Public Class ImportFileMethod
        Inherits BaseMethod

        Private ReadOnly Connection As SqlClient.SqlConnection
        Private ReadOnly Transaction As SqlClient.SqlTransaction

        Private User As UserState

        Public Sub New(pLogConfig As LogConfig, pDatabaseIDB As MSSQLServer, pDatabaseECM As MSSQLServer, pGlobalState As GlobalState)
            MyBase.New(pLogConfig, pDatabaseIDB, pDatabaseECM, pGlobalState)

            Connection = DatabaseIDB.GetConnection()
            Transaction = Connection.BeginTransaction()
        End Sub

        ''' <summary>
        ''' 
        ''' </summary>
        ''' <remarks>
        ''' 
        ''' 
        ''' 
        ''' </remarks>
        Public Function Run(pData As ImportFileRequest)
            Logger.Debug("Running [ImportFileMethod].")

            Try
                User = pData.User

                If pData.File Is Nothing Then
                    Throw New ArgumentNullException(NameOf(pData.File))
                End If

                If pData.KindType Is Nothing Then
                    Throw New ArgumentNullException(NameOf(pData.KindType))
                End If

                If pData.StoreName Is Nothing Then
                    Throw New ArgumentNullException(NameOf(pData.StoreName))
                End If

                If pData.User Is Nothing Then
                    Throw New ArgumentNullException(NameOf(pData.User))
                End If

                If IsNothing(pData.ProfileId) Then
                    Throw New ArgumentNullException(NameOf(pData.ProfileId))
                End If

                If IsNothing(pData.IDBDoctypeId) Then
                    Throw New ArgumentNullException(NameOf(pData.IDBDoctypeId))
                End If

                ' TODO: Add missing user properties in UserState from TBDD_USER
                'pData.User = ResolveUserFromUserName(pData.User.UserName)

                Dim oUserAttributes = pData.AttributeValues
                Dim oAutoAttributes As List(Of UserAttributeValue) = Nothing

                ' Import the file
                Dim oNewFile As New NewFile.NewFileMethod(LogConfig, DatabaseIDB, DatabaseECM, GlobalState)
                Dim oResponse = oNewFile.Run(New NewFile.NewFileRequest With {
                    .File = pData.File,
                    .IDBDoctypeId = pData.IDBDoctypeId,
                    .KindType = pData.KindType,
                    .StoreName = pData.StoreName,
                    .User = User
                })

                If oResponse.OK Then
                    Logger.Info("Import of file [{0}] under ObjectId [{1}] successful!", pData.File.FileName, oResponse.ObjectId)
                Else
                    Throw New ApplicationException(oResponse.ErrorMessage)
                End If

                ' Generate display Filename from nameconvention
                Dim oDisplayFilename = ""

                ' Generate virtual path from profile
                Dim oDynamicFilePath = ""

                Logger.Info("Collecting Attributes for ObjectId [{0}]", oResponse.ObjectId)

                Dim oFinalAttributes As New Dictionary(Of String, List(Of String))
                oFinalAttributes = Helpers.UserAttributesToDictionary(oUserAttributes)

                Logger.Info("Writing [{0}] Attributes for ObjectId [{0}] ", oResponse.ObjectId)
                Helpers.SetAttributeValuesWithTransaction(Connection, Transaction, oResponse.ObjectId, oFinalAttributes, User.Language, User.UserName)

                'TODO: Write to TBGI_INDEX_HISTORY?

                ' Finally, commit the transaction
                Transaction?.Commit()

                Return New ImportFileResponse(oResponse.ObjectId)

            Catch ex As Exception
                Logger.Warn("Error occurred while importing file!")
                Logger.Error(ex)

                Logger.Info("Rolling back transaction.")
                Transaction?.Rollback()

                Return New ImportFileResponse(ex)
            End Try
        End Function
    End Class

End Namespace