/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.servlet.facilities;

import java.io.PrintWriter;

import org.bodington.server.BuildingContext;
import org.bodington.server.BuildingServerException;
import org.bodington.server.BuildingSession;
import org.bodington.server.BuildingSessionManagerImpl;
import org.bodington.server.events.ResourceEvent;
import org.bodington.server.realm.Permission;
import org.bodington.server.realm.User;
import org.bodington.server.resources.HomeResource;
import org.bodington.server.resources.Resource;
import org.bodington.servlet.Request;
import org.bodington.util.html.HtmlFilterFactory;
import org.bodington.util.html.nodevisitors.ReportingVisitor;
import org.bodington.xml.XMLMetadataUtils;
import org.htmlparser.Parser;

public class HomeFacility extends Facility
{
    
    public Resource newResource()
    {
        return new HomeResource();
    }
    
    protected void confirmmodify(Request breq, PrintWriter out)
    {
        Resource resource;

        if (breq.getTemplateParameterCount() > 0)
        {
            out
                .println("<HR>The resource was NOT modified because the web address of the 'modify resource' "
                    + "page you came from is invalid.  This may have happened because you already changed "
                    + "the resource and you backtracked to an out-of-date page.  Please use the navigation "
                    + "bar to exit from here and review what changes have been made.<HR>");
            return;
        }

        if (!BuildingContext.getContext().checkPermission(Permission.MANAGE))
        {
            out
                .println("<PRE>You don't have permission to modify this location.</PRE>\n");
            return;
        }

        if (!breq.isAuthenticated())
        {
            out.println("<HR>Problem finding user.<HR>");
            return;
        }

        try
        {
            resource = BuildingContext.getContext().getResource();

            String description, introduction, keywords;

            description = breq.getParameter("description").trim();
            introduction = breq.getParameter("introduction").trim();
            keywords = breq.getParameter("keywords");

            if (description.length() == 0 || introduction.length() == 0)
            {
                out
                    .println("<HR>Unable to modify location - there must be text for title, description and introduction.<HR>");
                return;
            }

            Parser parser;
            ReportingVisitor visitor;

            parser = HtmlFilterFactory.getParser(description);
            visitor = HtmlFilterFactory.filter(parser,
                HtmlFilterFactory.FRAGMENT);
            if (visitor.getMessages().size() > 0)
            {
                printErrors(out, "Description", visitor.getMessages()
                    .iterator());
                return;
            }

            parser = HtmlFilterFactory.getParser(introduction);
            visitor = HtmlFilterFactory.filter(parser, HtmlFilterFactory.BODY);
            if (visitor.getMessages().size() > 0)
            {
                printErrors(out, "Introduction", visitor.getMessages()
                    .iterator());
                return;
            }

            parser = HtmlFilterFactory.getParser(keywords);
            visitor = HtmlFilterFactory.filter(parser,
                HtmlFilterFactory.FRAGMENT);
            if (visitor.getMessages().size() > 0)
            {
                printErrors(out, "Keywords", visitor.getMessages().iterator());
                return;
            }

            resource.setIntroduction(introduction);
            resource.setDescription(description);
            resource.save();

            // modify metadata record
            try
            {
                refreshMetadata(resource, XMLMetadataUtils
                    .extractKeywordsFromString(keywords));
            }
            catch (BuildingServerException bsex)
            {
                logException(out, "Facility", "confirmmodify",
                    "Unable to save the metadata: " + bsex.getMessage(), bsex);
            }

            ResourceEvent event = new ResourceEvent(ResourceEvent.EVENT_EDIT,
                resource);
            event.setActiveUser((User) BuildingContext.getContext().getUser());
            event.save();

            out.println("<B>Resource modified successfully.</B><BR />");
            out.println("<br />Please use one of the links below to reload all frames " 
                + "(the pages you are looking at may not reflect the new URL of the resource)<br /><br />" );
  
            out.print("Return to <A TARGET=_top title=\"Current resource\" HREF=\"");
            out.print( breq.getContextPath() );
            out.print( breq.getServletPath() );
            out.print( breq.getResource().getFullName() );
            out.print( "\">current</A> resource, or back to containing ");
            
            out.print("<A TARGET=_top title=\"Parent resource\" HREF=\"");
            out.print( breq.getContextPath() );
            out.print( breq.getServletPath() );
            out.print( breq.getResource().getParent().getFullName() );
            out.print( "\">parent</A> resource.");

            return;
        }
        catch (BuildingServerException bex)
        {
            out
                .println("<br />Unable to modify resource due to technical problem.");
        }

    }
}
