package com.example.backend.db.dao;

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

import com.example.backend.db.DB;
import com.example.backend.models.Book;

public class BookRepo implements BookRepoInterface {

    @Override
    public int addBook(Book b) {
        try (Connection con = DB.source().getConnection();
        PreparedStatement stm = con.prepareStatement("insert into books values (?,?,?,?)");) {
            stm.setString(1, b.getName());
            stm.setString(2, b.getAuthor());
            stm.setInt(3, b.getPages());
            stm.setInt(4, b.getLikes());
            return stm.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Book> getAllBooks() {
        try (Connection con = DB.source().getConnection();
        PreparedStatement stm = con.prepareStatement("select * from books");) {
            ResultSet rs = stm.executeQuery();
            List<Book> allBooks = new ArrayList<>();
            while(rs.next()){
                Book b = new Book(rs.getString("name"), rs.getString("author"), rs.getInt("pages"), rs.getInt("likes"));
                allBooks.add(b);
            }
            return allBooks;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int likeBook(Book b) {
        try (Connection con = DB.source().getConnection();
        PreparedStatement stm = con.prepareStatement("update books set likes = likes + 1 where name=?");) {
            stm.setString(1, b.getName());
            return stm.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }
    
}
