package dev.dao;

import dev.database.DatabaseConnection;
import dev.model.MenuItem;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MenuItemDao
{
    public List<MenuItem> findAll()
    {
        List<MenuItem> items = new ArrayList<>();

        String sql = "SELECT * FROM menu_items";

        try(Connection connection = DatabaseConnection.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql))
        {
            ResultSet rs = ps.executeQuery();

            while(rs.next())
            {
                MenuItem item = new MenuItem();

                item.setId(rs.getInt("id"));
                item.setName(rs.getString("name"));
                item.setDescription(rs.getString("description"));
                item.setPrice(rs.getDouble("price"));
                item.setCategory(rs.getString("category"));

                items.add(item);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }

        return items;
    }

    public MenuItem findById(int id)
    {
        String sql = "SELECT * FROM menu_items WHERE id=?";

        try(Connection connection = DatabaseConnection.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql))
        {
            ps.setInt(1,id);

            ResultSet rs = ps.executeQuery();

            if(rs.next())
            {
                MenuItem item = new MenuItem();

                item.setId(rs.getInt("id"));
                item.setName(rs.getString("name"));
                item.setDescription(rs.getString("description"));
                item.setPrice(rs.getDouble("price"));
                item.setCategory(rs.getString("category"));

                return item;
            }

        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }

        return null;
    }
}