package com.utopiaindustries.qualitychecker.db;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.utopiaindustries.qualitychecker.models.ItemUnit;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ItemRepository {

    private final DatabaseHelper dbHelper;
    private final SQLiteDatabase database;
    private final ExecutorService executorService;

    public ItemRepository( Context context ) {
        dbHelper = new DatabaseHelper ( context );
        database = dbHelper.getWritableDatabase();
        executorService = Executors.newSingleThreadExecutor();
    }


    /*
     *   Insert list of unit in batch
     * */
    public void insert( List<ItemUnit> units ) {
        executorService.execute(() -> {
            database.beginTransaction();
            try {
                for ( ItemUnit unit : units ) {
                    ContentValues values = new ContentValues();
                    values.put(DatabaseHelper.UNIT_COLUMN_ID, unit.getId() );
                    values.put(DatabaseHelper.UNIT_COLUMN_TITLE, unit.getTitle() );
                    database.insertWithOnConflict(DatabaseHelper.UNIT_TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE );
                }
                database.setTransactionSuccessful();
            } finally {
                database.endTransaction();
                close();
            }
        });
    }

    @SuppressLint("Range")
    public List<ItemUnit> findAll( ) {
        Cursor cursor = database.query( DatabaseHelper.UNIT_TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null);

        List<ItemUnit> units = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                ItemUnit unit = new ItemUnit();
                unit.setId(cursor.getLong( cursor.getColumnIndex(DatabaseHelper.UNIT_COLUMN_ID )));
                unit.setTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.UNIT_COLUMN_TITLE) ));
                units.add( unit );
            } while ( cursor.moveToNext() );
            cursor.close();
        }
        close();
        return units;
    }

    /*
     *  Close the database
     */
    public void close() {
        dbHelper.close();
        executorService.shutdown();
    }
}
