package admin.control;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.model.AnnounceInfo;
import admin.model.AnnounceMod;

/**
 * Servlet implementation class Announce
 */
public class Announce extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Announce() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
		response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8"); 
	    String rep = request.getParameter("rep");
	    String update = request.getParameter("update");
	    if(rep==null){rep="edit";}
	    
	    
	    if (rep.equals("edit")){
	    	try {
				AnnounceInfo an = new AnnounceMod().getAnnounce();
				request.setAttribute("announce", an);
				String url = "admin/index.jsp?main=edit-announce";
				if (update != null){url = "admin/index.jsp?main=edit-announce&upok=ok";}
				RequestDispatcher rd = request.getRequestDispatcher(url);
	            rd.forward(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			   
		   }
	    
	   if (rep.equals("update")){
		   Date date = new Date();
		    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy 'lúc' HH:mm:ss");
		    String adate = formatter.format(date);
		   String content = request.getParameter("content");
		   content = content.replaceAll("[%']", "");
		   new AnnounceMod().Update(adate, content);
		   response.sendRedirect("Announce?rep=edit&update=ok");
		   
	   }
	   
	   if (rep.equals("create")){
		   Date date = new Date();
		    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy 'lúc' HH:mm:ss");
		    String adate = formatter.format(date);
		   String content = request.getParameter("content");
		   content = content.replaceAll("[%']", "");
		   AnnounceInfo an = new AnnounceInfo(adate,content);
		   new AnnounceMod().CreateAnnounce(an);
		   response.sendRedirect("Announce?rep=edit");
	   }
	    	
	    	
	    

	}

}
