package dao;

import model.Product;
import utils.MysqlConnect;

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

public class ProductDAO {

    public List<Product> getProductList() throws SQLException {
        List<Product> result = new ArrayList<>();

        String sql = "SELECT * FROM products";

        Connection c = MysqlConnect.getConnecton();

        PreparedStatement pt = c.prepareStatement(sql);

        ResultSet rs = pt.executeQuery();

        while (rs.next()) {

            Product p = new Product(
                    rs.getInt("id"),
                    rs.getString("name"),
                    rs.getDouble("price"),
                    rs.getString("title"),
                    rs.getDate("created"),
                    rs.getString("catalog"),
                    rs.getBoolean("status")
            );

            result.add(p);

        }

        return result;
    }

    public Boolean createNewProduct(String name, Double price, String title, Date date, String catelog, Boolean status) throws SQLException {
       String sql = "INSERT INTO `products` (`id`, `name`, `price`, `title`, `created`, `catalog`, `status`) VALUES (NULL, ?, ?, ?, ?, ?, ?);";

       Connection c = MysqlConnect.getConnecton();

       PreparedStatement ps = c.prepareStatement(sql);

       ps.setString(1, name);
       ps.setDouble(2, price);
       ps.setString(3, title);
       ps.setDate(4, date);
       ps.setString(5, catelog);
       ps.setBoolean(6, status);

       int rows = ps.executeUpdate();

       if(rows > 0) {
           return true;
       }

       return false;
    }
}
