package com.zaojiao.app.data.local.di

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.core.DataStoreFactory
import androidx.datastore.dataStoreFile
import com.zaojiao.app.core.common.remote.AppDispatchers
import com.zaojiao.app.core.common.remote.Dispatcher
import com.zaojiao.app.core.common.remote.di.ApplicationScope
import com.zaojiao.app.data.local.BabyPreferences
import com.zaojiao.app.data.local.SettingsPreferences
import com.zaojiao.app.data.local.UserPreferences
import com.zaojiao.app.data.local.baby.BabyPreferencesSerializer
import com.zaojiao.app.data.local.settings.SettingsPreferencesSerializer
import com.zaojiao.app.data.local.user.UserPreferencesSerializer
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
class aLocalDataModule {
    /**
     *  用户信息 的本地存储
     */
    @Provides
    @Singleton
    fun providerUserPreferencesDataStore(
        @ApplicationContext context: Context,
        @Dispatcher(AppDispatchers.IO) ioDispatcher: CoroutineDispatcher,
        @ApplicationScope scope: CoroutineScope,
        userPreferencesSerializer: UserPreferencesSerializer,
    ): DataStore<UserPreferences> {
        return DataStoreFactory.create(
            serializer = userPreferencesSerializer,
            scope = CoroutineScope(scope.coroutineContext + ioDispatcher),
        ) {
            context.dataStoreFile("user_preferences.pb")
        }
    }

    /**
     *  宝贝幼儿 的本地存储
     */
    @Provides
    @Singleton
    fun providerBabyPreferencesDataStore(
        @ApplicationContext context: Context,
        @Dispatcher(AppDispatchers.IO) ioDispatcher: CoroutineDispatcher,
        @ApplicationScope scope: CoroutineScope,
        babyPreferencesSerializer: BabyPreferencesSerializer,
    ): DataStore<BabyPreferences> {
        return DataStoreFactory.create(
            serializer = babyPreferencesSerializer,
            scope = CoroutineScope(scope.coroutineContext + ioDispatcher),
        ) {
            context.dataStoreFile("baby_preferences.pb")
        }
    }

    /**
     *  设置 的本地存储
     */
    @Provides
    @Singleton
    fun providerSettingsPreferencesDataStore(
        @ApplicationContext context: Context,
        @Dispatcher(AppDispatchers.IO) ioDispatcher: CoroutineDispatcher,
        @ApplicationScope scope: CoroutineScope,
        settingsPreferencesSerializer: SettingsPreferencesSerializer,
    ): DataStore<SettingsPreferences> {
        return DataStoreFactory.create(
            serializer = settingsPreferencesSerializer,
            scope = CoroutineScope(scope.coroutineContext + ioDispatcher),
        ) {
            context.dataStoreFile("settings_preferences.pb")
        }
    }
}