package org.mercury_im.messenger.cli.di.module;

import org.h2.jdbcx.JdbcDataSource;
import org.mercury_im.messenger.core.SchedulersFacade;
import org.mercury_im.messenger.data.model.Models;

import java.util.concurrent.Executors;

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

import dagger.Module;
import dagger.Provides;
import io.reactivex.Scheduler;
import io.reactivex.schedulers.Schedulers;
import io.requery.Persistable;
import io.requery.cache.EmptyEntityCache;
import io.requery.reactivex.ReactiveEntityStore;
import io.requery.reactivex.ReactiveSupport;
import io.requery.sql.Configuration;
import io.requery.sql.ConfigurationBuilder;
import io.requery.sql.EntityDataStore;
import io.requery.sql.SchemaModifier;
import io.requery.sql.TableCreationMode;

@Module
public class CliDatabaseModule {

    @Provides
    @Singleton
    static ReactiveEntityStore<Persistable> provideDatabase() {
        JdbcDataSource dataSource = new JdbcDataSource();
        dataSource.setUrl("jdbc:h2:~/mercury_req_db");
        dataSource.setUser("sa");
        dataSource.setPassword("sa");

        // override onUpgrade to handle migrating to a new version
        Configuration configuration = new ConfigurationBuilder(dataSource, Models.DEFAULT)
                //.useDefaultLogging()
                .setEntityCache(new EmptyEntityCache())
                .setWriteExecutor(Executors.newSingleThreadExecutor())
                .build();

        SchemaModifier tables = new SchemaModifier(configuration);
        tables.createTables(TableCreationMode.DROP_CREATE);
        System.out.println(tables.createTablesString(TableCreationMode.DROP_CREATE));

        return ReactiveSupport.toReactiveStore(new EntityDataStore<>(configuration));
    }

}
