package com.seven.ikar.kotlin.app

import android.app.Application
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.disk.DiskCache
import coil.memory.MemoryCache
import coil.request.CachePolicy
import com.seven.ikar.kotlin.core.push.AndroidPushBootstrapper
import java.io.File
import kotlinx.coroutines.launch

class IkarNativeApp : Application(), ImageLoaderFactory {
    lateinit var container: AppContainer
        private set

    override fun onCreate() {
        super.onCreate()
        AndroidPushBootstrapper.tryInitialize(this)
        container = AppContainer(this)
        container.applicationScope.launch {
            container.pushRegistrationManager.initializeAsync()
            if (container.sessionStore.read() != null) {
                runCatching { container.pushRegistrationManager.registerCurrentDeviceAsync() }
            }
        }
    }

    override fun newImageLoader(): ImageLoader =
        ImageLoader.Builder(this)
            .callFactory { container.httpClient }
            .memoryCache {
                MemoryCache.Builder(this)
                    .maxSizePercent(0.25)
                    .build()
            }
            .diskCache {
                DiskCache.Builder()
                    .directory(File(cacheDir, "image_cache"))
                    .minimumMaxSizeBytes(64L * 1024L * 1024L)
                    .maximumMaxSizeBytes(256L * 1024L * 1024L)
                    .maxSizePercent(0.03)
                    .build()
            }
            .memoryCachePolicy(CachePolicy.ENABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .networkCachePolicy(CachePolicy.ENABLED)
            .respectCacheHeaders(false)
            .crossfade(true)
            .build()
}
