package src.hibernatebb.web;

import src.hibernatebb.discussion.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*; // for List and Iterator

public class PostPostServlet extends HttpServlet {

    public void doPost(HttpServletRequest request,
		       HttpServletResponse response)
	throws IOException, ServletException {
	
	RequestDispatcher view;
	HttpSession session = request.getSession(false);
	BoardManager bm = new BoardManager();
	  
	String userName = request.getParameter("name");
	String topicSelected = request.getParameter("topicselected");
	String subject = request.getParameter("subject");
	String body = request.getParameter("body");

        Topic currentTopic = new Topic(bm.loadTopic(topicSelected));

	try {


	    User poster = bm.loadUser(userName);
	    
	    Post p = new Post(poster, subject, body);
	    bm.savePost(p);

	    currentTopic.addPost(p);
	    bm.saveTopic(currentTopic);
	}
	catch(Exception e) {

	}

	String allPosts = "";

	List posts = currentTopic.getPosts();

	ListIterator it = posts.listIterator();
	Post thisPost = new Post();
	User author;

	while(it.hasNext()) {
	    thisPost = (Post)it.next();
	    author = thisPost.getPoster();
	    allPosts += "Author:\t" + author.getID() + "<br />";
	    allPosts += "Date:\t" + thisPost.getTimestamp() + "<br />";
	    allPosts += "Subject:\t"+ thisPost.getSubject() + "<br />";
	    allPosts += "Body:\t" + thisPost.getBody() + "<br /><br />";
	}
	

       	request.setAttribute("topicselected", topicSelected);
        request.setAttribute("name", userName);
      	request.setAttribute("posts", allPosts);

	view = request.getRequestDispatcher("viewtopic.jsp");	

	view.forward(request, response);
    }
}

