package com.lovecoding.mvc.model;

import com.lovecoding.mvc.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.validation.BeanPropertyBindingResult;

import java.util.List;
import java.util.Map;

@Repository
public class BookMapper implements Book {

    @Autowired
    JdbcTemplate jdbcTemplatel;

    @Override
    public int add(BookDao book) {
        Object[] insert = new Object[] {
                book.getBook_name(),
                book.getPrice(),
                book.getStock()
        };
        String sql = "INSERT INTO`t_book` (`book_name`, `price`, `stock`) VALUES (?, ?, ?)";
        int update = jdbcTemplatel.update(sql, insert);
        return update;
    }

    @Override
    public int del(Long bookId) {
        Object[] id = new Object[]{bookId};
        String sql = "DELETE FROM `t_book` WHERE `book_id` = ?";
        int update = jdbcTemplatel.update(sql, id);
        return update;
    }

    @Override
    public int update(BookDao book) {
        Object[] args = new Object[]{
                book.getBook_name(),
                book.getPrice(),
                book.getStock(),
                book.getBook_id()
        };
        String sql = "UPDATE `t_book` SET book_name = ?, price = ?, stock = ?  WHERE `book_id` = ? ";
        int update = jdbcTemplatel.update(sql, args);
        System.out.println( update );
        System.out.println( book );
        return update;
    }

    @Override
    public BookDao get(Long bookId) {
        String sql = "SELECT book_id, book_name, price, stock FROM `t_book` WHERE book_id = ?";
        Object[] id = new Object[]{bookId};
        BookDao bookDao = jdbcTemplatel.queryForObject(
                sql, id, new BeanPropertyRowMapper<BookDao>(BookDao.class));
        return bookDao;
    }


    public List<Map<String, Object>> get() {
        String sql = "SELECT book_id, book_name, price, stock  FROM `t_book`";
        List<Map<String, Object>> maps = jdbcTemplatel.queryForList(sql);
        return maps;
    }
}
