package dev.dao;

import dev.model.MenuItem;

import java.util.List;
import dev.database.DatabaseConnection;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

public class MenuItemDao {

    public List<MenuItem> findAll() {

        // TODO:
        // Retrieve all menu items
        List<MenuItem> items = new ArrayList<>();
        String sql = "SELECT * FROM menu_items";
        try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery()){
            while (rs.next()) {
                MenuItem item = new MenuItem();
                mapResultSetToMenuItem(rs, item);
                items.add(item);
            }
        }
        catch (SQLException ex){
            ex.printStackTrace();
        }
        return items;
    }

    public MenuItem findById(int id) {

        // TODO:
        // Find menu item by id
        String sql = "SELECT * FROM menu_items WHERE id = ?";
        try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)){
            stmt.setInt(1, id);
            try (ResultSet rs = stmt.executeQuery()){
                if (rs.next()){
                    MenuItem item = new MenuItem();
                    mapResultSetToMenuItem(rs, item);
                    return item;
                }
            }
        }
        catch (SQLException ex){
            ex.printStackTrace();
        }
        return null;
    }
    private void mapResultSetToMenuItem(ResultSet rs, MenuItem item){
        try {
            Field idField = MenuItem.class.getDeclaredField("id");
            Field nameField = MenuItem.class.getDeclaredField("name");
            Field descField = MenuItem.class.getDeclaredField("description");
            Field priceField = MenuItem.class.getDeclaredField("price");
            Field catField = MenuItem.class.getDeclaredField("category");
            idField.setAccessible(true);
            nameField.setAccessible(true);
            descField.setAccessible(true);
            priceField.setAccessible(true);
            catField.setAccessible(true);
            idField.set(item, rs.getInt("id"));
            nameField.set(item, rs.getString("name"));
            descField.set(item, rs.getString("description"));
            priceField.set(item, rs.getDouble("price"));
            catField.set(item, rs.getString("category"));
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
}