package com.perpus.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.perpus.dao.BukuDAO;
import com.perpus.dao.BukuDAOImplementation;
import com.perpus.model.Buku;

@WebServlet("/BukuController")
public class BukuController extends HttpServlet 
{
	private BukuDAO dao;
    private static final long serialVersionUID = 1L;
    public static final String LIST_BUKU = "/listBku.jsp";
    public static final String INSERT_OR_EDIT = "/buku.jsp";
 
    public BukuController() {
        dao = new BukuDAOImplementation();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String forward = "";
        String action = request.getParameter( "action" );
 
        if( action.equalsIgnoreCase( "delete" ) ) {
            forward = LIST_BUKU;
            int idBuku = Integer.parseInt( request.getParameter("idBuku") );
            dao.deleteBuku(idBuku);
            request.setAttribute("bukus", dao.getAllBukus() );
        }
        else if( action.equalsIgnoreCase( "edit" ) ) {
            forward = INSERT_OR_EDIT;
            int idBuku = Integer.parseInt( request.getParameter("idBuku") );
            Buku buku = dao.getBukuById(idBuku);
            request.setAttribute("buku", buku);
        }
        else if( action.equalsIgnoreCase( "insert" ) ) {
            forward = INSERT_OR_EDIT;
        }
        else {
            forward = LIST_BUKU;
            request.setAttribute("bukus", dao.getAllBukus() );
        }
        RequestDispatcher view = request.getRequestDispatcher( forward );
        view.forward(request, response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		Buku buku = new Buku();
        buku.setJudulBuku(request.getParameter("judulBuku"));
        buku.setPengarangBuku(request.getParameter("pengarangBuku"));
        buku.setIsbn(request.getParameter("isbn"));
        buku.setJumlah(Integer.parseInt(request.getParameter("jumlah")));
        String idBuku = request.getParameter("idBuku");
 
        if(idBuku == null || idBuku.isEmpty() )
            dao.addBuku(buku);
        else 
        {
            buku.setIdBuku(Integer.parseInt(idBuku));
            dao.updateBuku(buku);
        }
        RequestDispatcher view = request.getRequestDispatcher(LIST_BUKU);
        request.setAttribute("students", dao.getAllBukus());
        view.forward(request, response);
	}
}
