package net.buzzert.kordophonedroid

import android.content.Context
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import net.buzzert.kordophone.backend.db.CachedChatDatabase
import net.buzzert.kordophone.backend.server.APIClientFactory
import net.buzzert.kordophone.backend.server.ChatRepository
import net.buzzert.kordophonedroid.ui.attachments.AttachmentImageLoader
import net.buzzert.kordophonedroid.ui.shared.ServerConfigRepository
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Singleton
    @Provides
    fun provideChatRepository(configRepository: ServerConfigRepository): ChatRepository {
        val serverConfig = configRepository.serverConfig.value

        val server = serverConfig.serverName
        val authentication = serverConfig.authentication?.toBackendAuthentication()
        val client = APIClientFactory.createClient(server, authentication)

        val database = CachedChatDatabase.liveDatabase()
        return ChatRepository(client, database)
    }

    @Singleton
    @Provides
    fun provideAttachmentFactory(
        chatRepository: ChatRepository,
        @ApplicationContext context: Context
    ): AttachmentImageLoader
    {
        return AttachmentImageLoader(chatRepository, context)
    }
}