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.InspectionDefect;

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

public class DefectRepository {

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

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


    /*
     *   Insert list of defects in batch
     * */
    public void insert( List<InspectionDefect> defects ) {
        executorService.execute(() -> {
            database.beginTransaction();
            try {
                for ( InspectionDefect defect : defects ) {
                    ContentValues values = new ContentValues();
                    values.put(DatabaseHelper.DEFECT_COLUMN_DEFECT, defect.getDefect() );
                    values.put(DatabaseHelper.DEFECT_COLUMN_CATEGORY, defect.getCategory() );
                    database.insertWithOnConflict(DatabaseHelper.DEFECT_TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                }
                database.setTransactionSuccessful();
            } finally {
                database.endTransaction();
                close();
            }
        });
    }

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

        List<InspectionDefect> defects = new ArrayList<>();
        if ( cursor != null && cursor.moveToFirst() ) {
            do {
                InspectionDefect defect = new InspectionDefect();
                defect.setCategory( cursor.getString( cursor.getColumnIndex(DatabaseHelper.DEFECT_COLUMN_CATEGORY )));
                defect.setDefect( cursor.getString( cursor.getColumnIndex(DatabaseHelper.DEFECT_COLUMN_DEFECT) ));
                defects.add( defect );
            } while ( cursor.moveToNext() );
            cursor.close();
        }
        close();
        return defects;
    }

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