package app.issue.commons.sqlite;

import android.database.Cursor;
import android.support.annotation.Nullable;

import com.google.common.base.Function;

@SuppressWarnings("Guava")
public class CursorProcessor {

    private CursorProcessor() {
    }

    @Nullable
    public static <T> T process(@Nullable Cursor cursor, Function<Cursor, T> cursorToValue) {
        if (cursor == null) {
            return null;
        }
        try {
            if (cursor.moveToFirst()) {
                return cursorToValue.apply(cursor);
            }
        } finally {
            cursor.close();
        }
        return null;
    }

    public static Long processLong(Cursor cursor, String columnName) {
        return CursorProcessor.process(cursor, input -> cursor.getLong(input.getColumnIndex(columnName)));
    }

    public static String processString(Cursor cursor, String columnName) {
        return CursorProcessor.process(cursor, input -> cursor.getString(input.getColumnIndex(columnName)));
    }
}
