package org.apache.jetspeed.portal.controls;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */


//ECS stuff
import org.apache.ecs.html.IMG;
import org.apache.ecs.html.B;
import org.apache.ecs.html.Table;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.ConcreteElement;
import org.apache.ecs.ElementContainer;


//jetspeed support
import org.apache.jetspeed.util.JetspeedException;
import org.apache.jetspeed.util.MimeType;
import org.apache.jetspeed.util.URILookup;
import org.apache.jetspeed.capability.CapabilityMap;
import org.apache.jetspeed.capability.CapabilityMapFactory;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.resources.JetspeedResources;

//turbine
import org.apache.turbine.util.ContentURI;
import org.apache.turbine.util.RunData;

//java imports
import java.util.Vector;

/**
 <p>
 This control renders the title of a portlet for MimeTyps WML and HTML.
 For WML only the title (represented as a link) is returned. In case that
 the device requests html the title will be rendered within a titlebar (with
 buttons for editing or maximizing the portlet).
 </p>
 @author <a href="mailto:sasalda@de.ibm.com">Sascha Alda</a>
 @author <a href="mailto:stephan.hesmer@de.ibm.com">Stephan Hesmer</a>     
 @author <a href="mailto:sgala@apache.org">Santiago Gala</a>     
 @version $Id: TitleControl.java,v 1.13 2003/07/23 19:50:16 morciuch Exp $
*/
public class TitleControl extends AbstractPortletControl {
                
    /**
     * Static initialization of the logger for this class
     */    
    private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(TitleControl.class.getName());    
    
    /**
       Method checks, which MimeType is requested. According to this MimeTyp, the
       appropriate method is invoked (getWMLContent() or getHTMLContent() ).
       @param rundata  RunData object from Turbine.
       @return ConcreteElement object, including the complete ECS code for rendering
       the page.
    */              
    public ConcreteElement getContent( RunData rundata ) {
        CapabilityMap cm = CapabilityMapFactory.getCapabilityMap( rundata );
        if ( cm.getPreferredType().equals( MimeType.HTML ) ) {
            return getHTMLContent( rundata );
        }
        if ( cm.getPreferredType().equals( MimeType.WML ) ) {
            return getWMLContent( rundata );
        }
        logger.error("The Given MIME-Type is not supportet for this control");
        return null;
    }


    /**
       Method returns content for html, in case that the requested MimeTyp is html.
       @param rundata  RunData object from Turbine.
       @return ConcreteElement object, including the complete ECS code for rendering
       the html page.
    */        
    public ConcreteElement getHTMLContent( RunData rundata ) {
        //embed this here
        ElementContainer base = new ElementContainer();

        //the overall portlet...
        Table t = new Table()
            .setBgColor( this.getColor() )
            .setBorder(0)
            .setCellPadding(1)
            .setCellSpacing(0)
            .setWidth( getWidth() )
            .setAlign( "center" );


        ConcreteElement[] options = this.getPortletOptions( rundata );

        TR finalTitle = new TR()
            .setBgColor( this.getTitleColor() )
            .addElement( new TD()
                .setBgColor( this.getTitleColor() )
                .setNoWrap( true )
                .setWidth("100%")
                .setVAlign("middle")
                .addElement( new B()
                    .addElement( getPortlet().getTitle() )
                    .addElement("  ") ) );

        if ( options.length > 0 ) {

            ElementContainer alloptions = new ElementContainer();
            for (int i = 0; i < options.length; ++i) {
                alloptions.addElement( options[i] );
            }

            finalTitle.addElement( new TD()
                .setBgColor( this.getTitleColor() )
                .setNoWrap( true )
                .setAlign("right")
                .setVAlign("middle")
                .addElement( alloptions ) );

        }



        t.addElement( finalTitle );

        base.addElement( t );

        return base;
    }
         
    /**
       Method returns content for WML, in case that the requested MimeTyp is WML.
       @param rundata  RunData object from Turbine.
       @return ConcreteElement object, including the complete ECS code for rendering
       the html page.
    */   
    public ConcreteElement getWMLContent( RunData rundata ) {
        ElementContainer ec = new ElementContainer();
        try {
            ec.addElement(new org.apache.ecs.wml.P()
                .addElement(
                            new org.apache.ecs.wml.A(
                                                     URILookup.getURI( URILookup.TYPE_HOME, 
                                                                       URILookup.SUBTYPE_MAXIMIZE, 
                                                                       getName(),
                                                                       rundata ) )
                                .addElement( getTitle() ) ) );
        }
        catch (JetspeedException e) {
            logger.error("Exception", e);
        }
        return ec;
    }

                
    /**
       Method returns the title of the portlet, which is placed within this control.
       @return String object, representing the portlet's title.
    */      
    public String getTitle(){
        return getPortlet().getTitle();
    }

    /**
       Method checks whether the requested MimeTyp is supported by this control.
       Moreover, it checks, if the included portlet fits the given MimeTyp as well.
       Thus, the method returns true, iff both the control and the portlet(set) support
       the requested MimeType. Otherwise false is returned.
       @param mimeType   MimeType object describing the requested MimeTyp.
       @return Boolean true if MimeTyp is supported, false if not.
    */
    public boolean supportsType( MimeType mimeType ) {
        if ( (!MimeType.HTML.equals( mimeType )) &&
             (!MimeType.WML.equals( mimeType )) ){
            return false;
        }
        // Call of the same method of control's portlet
        return getPortlet().supportsType( mimeType );   
    }

    /**
       Get the options for this portlet.
    */
    private ConcreteElement[] getPortletOptions( RunData rundata ) {

        Vector v = new Vector();
        ContentURI content = new ContentURI( rundata );

        int type = URILookup.getURIType(this.getPortlet(),
                                        rundata);
        int subtype = URILookup.SUBTYPE_NONE;
        try {
            subtype = URILookup.getURISubType(this.getPortlet(),
                                              rundata);
        }
        catch (JetspeedException e) {
            logger.error("Exception", e);
        }

        if ( type != URILookup.TYPE_EDIT_ACCOUNT) {
            if ( ( rundata.getUser() != null ) &&
                 ( rundata.getUser().hasLoggedIn()) ) {
                if ( this.getPortlet().getAllowEdit( rundata ) ) {
                    if (type!=URILookup.TYPE_INFO) {
                        try {
                            org.apache.ecs.html.A edit = 
                                new org.apache.ecs.html.A( 
                                                          URILookup.getURI( URILookup.TYPE_INFO,
                                                                            URILookup.SUBTYPE_MARK,
                                                                            this.getPortlet(),
                                                                            rundata ) )
                                    .addElement( new IMG( content.getURI( JetspeedResources.INFO_IMAGE ) )
                                        .setBorder( 0 ) );

                            v.addElement( edit );
                        }
                        catch (JetspeedException e) {
                            logger.error("Exception", e);
                        }
                    }
                }
                
            }

            if ( this.getPortlet().getAllowMaximize( rundata ) ) {
                try {
                    if ( subtype != URILookup.SUBTYPE_MAXIMIZE ) {
                        org.apache.ecs.html.A max = 
                            new org.apache.ecs.html.A( 
                                                      URILookup.getURI( URILookup.TYPE_HOME,
                                                                        URILookup.SUBTYPE_MAXIMIZE,
                                                                        this.getPortlet(),
                                                                        rundata ) )
                                .addElement( new IMG( content.getURI( JetspeedResources.MAX_IMAGE ) )
                                    .setBorder( 0 ) );

                        v.addElement( max );
                    }
                }
                catch (JetspeedException e) {
                    logger.error("Exception", e);
                }
            }
        }

        ConcreteElement[] elements = new ConcreteElement[v.size()];
        v.copyInto(elements);
        return elements;
    }


                
}
