package com.m2sdl.undercooked.domain;

import android.database.sqlite.SQLiteDatabase;

import org.mapsforge.core.model.LatLong;

// TODO move to a Room based approach if possible
public class PoiRepository {

    private final String[] columns = {"restaurant_data", "category", "latitude", "longitude"};
    private final String selection = "round(?1 , 5) = round(restaurants.latitude, 5) and round(?2, 5) = round(restaurants.longitude, 5)";
    private final SQLiteDatabase db;

    public PoiRepository(String dataPath) {
        db = SQLiteDatabase.openDatabase(dataPath, null, SQLiteDatabase.OPEN_READONLY);
    }

    public Restaurant findRestaurantByPosition(LatLong position) {
        var cursor = db.query("restaurants",
                columns,
                selection,
                new String[]{Double.toString(position.latitude), Double.toString(position.longitude)},
                null, null, null, "1"
        );
        if (cursor.getCount() < 1) {
            return new Restaurant();
        } else {
            cursor.moveToNext();
            Restaurant r = new Restaurant();
            r.parseData(cursor.getString(0));
            r.setCategorie(cursor.getString(1));
            r.setPosition(position);
            cursor.close();
            return r;
        }
    }

    public void close() {
        db.close();
    }

}
