Imports System.IO
Imports DigitalData.Modules.EDMI.API.EDMIServiceReference
Imports DigitalData.Modules.Logging

Namespace Modules.IDB
    Public Class ImportFile
        Inherits BaseMethod

        Public Sub New(pLogConfig As LogConfig, pChannel As IEDMIServiceChannel)
            MyBase.New(pLogConfig, pChannel)
        End Sub

        Public Async Function RunAsync(pFilePath As String,
                                       pAttributeValues As List(Of UserAttributeValue),
                                       pObjectStoreName As String,
                                       pObjectKind As String,
                                       pIDBDoctypeId As Long,
                                       pImportOptions As Options.ImportFileOptions) As Task(Of ImportFileResponse)
            Try
                ' Set default options
                If pImportOptions Is Nothing Then
                    pImportOptions = New Options.ImportFileOptions()
                End If

                ' Check if file exists
                If File.Exists(pFilePath) = False Then
                    Throw New FileNotFoundException("Path does not exist")
                End If

                ' Try to load file properties
                Dim oFileProperties = Helpers.GetFileProperties(pFilePath, pImportOptions.DateImported)
                If oFileProperties Is Nothing Then
                    Throw New IOException("File could not be read!")
                End If

                ' Importing the file now
                Dim oFileImportResponse = Await Channel.ImportFileAsync(New ImportFileRequest With {
                    .IDBDoctypeId = pIDBDoctypeId,
                    .File = oFileProperties,
                    .KindType = pObjectKind,
                    .StoreName = pObjectStoreName,
                    .User = New UserState() With {
                        .UserName = pImportOptions.Username,
                        .Language = pImportOptions.Language
                    },
                    .ProfileId = -1,
                    .AttributeValues = pAttributeValues.ToArray
                })

                Return oFileImportResponse

            Catch ex As Exception
                Logger.Error(ex)
                Return Nothing

            End Try
        End Function
    End Class
End Namespace

