package org.mercury_im.messenger.di.module;

import android.app.Application;

import org.mercury_im.messenger.data.model.Models;
import org.mercury_im.messenger.util.ThreadUtils;
import org.mercury_im.messenger.BuildConfig;

import javax.inject.Named;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.requery.Persistable;
import io.requery.android.sqlite.DatabaseSource;
import io.requery.reactivex.ReactiveEntityStore;
import io.requery.reactivex.ReactiveSupport;
import io.requery.sql.Configuration;
import io.requery.sql.EntityDataStore;
import io.requery.sql.TableCreationMode;

@Module
public class AndroidPersistenceModule {

    @Provides
    @Singleton
    static ReactiveEntityStore<Persistable> provideDatabase(Application application) {
        // override onUpgrade to handle migrating to a new version
        DatabaseSource source = new DatabaseSource(application, Models.DEFAULT, "mercury_req_db", 1);
        if (BuildConfig.DEBUG) {
            source.setTableCreationMode(TableCreationMode.DROP_CREATE);
        }
        Configuration configuration = source.getConfiguration();
        return ReactiveSupport.toReactiveStore(new EntityDataStore<>(configuration));
    }

    @Provides
    @Named(value = ThreadUtils.SCHEDULER_IO)
    @Singleton
    static Scheduler provideDatabaseThread() {
        return Schedulers.io();
    }

    @Provides
    @Named(value = ThreadUtils.SCHEDULER_UI)
    @Singleton
    static Scheduler providerUIThread() {
        return AndroidSchedulers.mainThread();
    }
}
