package oracle.portal.sample.v1.devguide.helloservletworld;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import oracle.portal.provider.v1.*;
import oracle.portal.provider.v1.http.*;

public class EditServlet extends HttpServlet
{

    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        doGet(req, res);
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
        PortletRenderRequest pr = (PortletRenderRequest)req.getAttribute(HttpProvider.PORTLET_RENDER_REQUEST);
        switch(pr.getMode())
        {
        case PortletRenderer.MODE_EDIT:
            renderEdit(pr);
            break;
        case PortletRenderer.MODE_EDIT_DEFAULTS:
            renderEditDefaults(pr);
            break;
        default:
            throw new ServletException("Incorrect mode supplied!!");
        }
    }

    private void renderEdit(PortletRenderRequest pr)
    {
        try
        {
            PrintWriter out = pr.getWriter();
            String actionParam = PortletRendererUtil.getEditFormParameter(pr);
            String action = pr.getParameter(actionParam);
            ProviderSession session = pr.getSession();
            ServletPersonalization data = (ServletPersonalization)PortletRendererUtil.getEditData(pr);
            if (action != null)
            {
                data.setPortletTitle(pr.getParameter("hw_title"));
                PortletRendererUtil.submitEditData(pr, data);

                // write into session indication that cache is now invalid
                if(session != null)
                {
                    session.putValue(PortletRendererUtil.portletParameter(pr.getPortletReference(), "hasChanged"), new Boolean(true));
                }
            }
            else
            {
                out.println("<table BORDER CELLSPACING=0>");
                out.println("<tr><td>Title:</td><td><INPUT TYPE=\"text\" "+
                            "SIZE=\"40\" MAXLENGTH=\"60\" NAME=\"hw_title" + "\" VALUE=\""
                            + data.getPortletTitle() + "\" /></td></tr>");
            }
        }
        catch (Exception e)
        {
        }

    }

    private void renderEditDefaults(PortletRenderRequest pr)
    {
        renderEdit(pr);
    }

}
