package dev.dao;

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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MenuItemDao {

    public List<MenuItem> findAll() {

        String sql = "SELECT * FROM menu_items";
        List<MenuItem> items = new ArrayList<>();

        try (PreparedStatement ps = DatabaseConnection
                                    .getConnection()
                                    .prepareStatement(sql))
        {
            ResultSet rs = ps.executeQuery();
            while (rs.next())
            {
                MenuItem menuItem = new MenuItem();
                menuItem.setId(rs.getInt("id"));
                menuItem.setName(rs.getString("name"));
                menuItem.setDescription(rs.getString("description"));
                menuItem.setPrice(rs.getDouble("price"));
                menuItem.setCategory(rs.getString("category"));

                items.add(menuItem);
            }

        } catch (SQLException e) {

            System.out.println(e.getStackTrace());
        }

        return items;
    }

    public MenuItem findById(int id) {

        String sql = "SELECT * FROM menu_items WHERE id=?";

        try(PreparedStatement ps = DatabaseConnection
                .getConnection()
                .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;
    }

}