/*
 * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details.
 */

package at.bitfire.davdroid.di

import android.content.Context
import at.bitfire.davdroid.ProductIds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import net.openid.appauth.AppAuthConfiguration
import net.openid.appauth.AuthorizationService
import java.net.HttpURLConnection
import java.net.URL

/**
 * AppAuth-Android integration
 */
@Module
@InstallIn(SingletonComponent::class)
class AuthorizationServiceModule {

    /**
     * Make sure to call [net.openid.appauth.AuthorizationService.dispose] when obtaining an instance.
     *
     * Creating an instance is expensive (involves CustomTabsManager), so don't create an
     * instance if not necessary (use Provider/Lazy).
     */
    @Provides
    fun authorizationService(
        @ApplicationContext context: Context,
        productIds: ProductIds
    ): AuthorizationService =
        AuthorizationService(
            context,
            AppAuthConfiguration.Builder()
                .setConnectionBuilder { uri ->
                    val url = URL(uri.toString())
                    (url.openConnection() as HttpURLConnection).apply {
                        setRequestProperty("User-Agent", productIds.httpUserAgent)
                    }
                }.build()
        )

}