/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 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/>.
 */

package org.apache.jetspeed.modules.actions.portlets;

// Velocity stuff
import org.apache.jetspeed.portal.portlets.VelocityPortlet;
import org.apache.jetspeed.modules.actions.portlets.VelocityPortletAction;

import org.apache.turbine.util.RunData;

// Velocity Stuff
import org.apache.velocity.context.Context;

//Java stuff
import java.util.StringTokenizer;

/**
 * WeatherAction portlet uses WeatherUnderground's weather condition
 * stickers/banners to build the portlet view.
 *
 * <p> Donated by Community Grids Java Source Package</p>
 * <p> Provides supporting classess for portal environments.</p>
 *
 * @author <a href="mailto:obalsoy@indiana.edu">Ozgur Balsoy</a>
 * @version $Id: WeatherAction.java,v 1.4 2003/03/04 00:04:53 sgala Exp $
 */
public class WeatherAction extends VelocityPortletAction
{
    
    /**
     * Nothing specific for maximized view.
     *
     * @see VelocityPortletAction#buildMaximizedContext
     */
    protected void buildMaximizedContext( VelocityPortlet portlet,
                                          Context context,
                                          RunData rundata )
    {
        buildNormalContext( portlet, context, rundata);
    }
    
    /**
     * Subclasses should override this method if they wish to
     * provide their own customization behavior.
     * Default is to use Portal base customizer action
     *
     * @see VelocityPortletAction#buildConfigureContext
     */
    protected void buildConfigureContext( VelocityPortlet portlet,
                                          Context context,
                                          RunData rundata )
    {
        buildNormalContext( portlet, context, rundata);
        String cityInfo = (String)context.get("weather_city_info");
        if(cityInfo != null)
        {
            try
            {
                javax.naming.Name path = new javax.naming.CompositeName(cityInfo);
                if(path.size()==3)
                {
                    if(path.get(0).equals("US"))
                    {
                        context.put("weather_state",path.get(1));
                        context.put("weather_city",path.get(2).replace('_',' '));
                    } else
                    {
                        context.put("weather_station",path.get(2));
                    }
                }
            }
            catch(Exception ex)
            {}
        }
        setTemplate(rundata, "weather-customize");
    }
    
    /**
     * Subclasses must override this method to provide default behavior
     * for the portlet action
     *
     * @see VelocityPortletAction#buildNormalContext
     */
    protected void buildNormalContext( VelocityPortlet portlet,
                                       Context context,
                                       RunData rundata )
    {
        String cityInfo = portlet.getAttribute("weather_city_info",null, rundata);
        if( cityInfo == null)
        {
            String city = portlet.getPortletConfig().getInitParameter("weather_city");
            String state = portlet.getPortletConfig().getInitParameter("weather_state");
            String station = portlet.getPortletConfig().getInitParameter("weather_station");
            cityInfo = getCityInfo(city, state, station);
            if(cityInfo == null)
            {
                setTemplate(rundata, "weather-customize");
                return;
            }
            else
            {
                portlet.setAttribute("weather_city_info",cityInfo, rundata);
            }
        }
        context.put("weather_city_info", cityInfo);
        String style = portlet.getAttribute("weather_style",null,rundata);
        if(style == null)
        {
            style = portlet.getPortletConfig().getInitParameter("weather_style");
            if(style == null)
            {
                style = "infobox";
                portlet.setAttribute("weather_style",style,rundata);
            }
        }
        context.put("weather_style",style);
    }
    
    /**
     * Builds the path for US cities. The format is US/ST/City.html, i.e.
     * for New York City, the city path is US/NY/New_York
     */
    private String getUSInfo(String city, String state)
    {
        city = city.trim().toLowerCase()+" ";
        if(city.indexOf(" ")>0)
        {
            String newCity = "";
            StringTokenizer st = new StringTokenizer(city, " ");
            while(st.hasMoreTokens())
            {
                String token = st.nextToken();
                newCity = newCity + token.substring(0,1).toUpperCase() +
                token.substring(1) + "_";
            }
            city = newCity.substring(0, newCity.length()-1); // remove last '_'
        }
        state = state.toUpperCase();
        return "US/" + state + "/" + city;
    }
    
    /**
     * Builds the city path for US or other world cities. For world cities,
     * the city path is global/station/station_number, i.e.
     * for Istanbul, Turkey, it is global/stations/17060. The station numbers
     * need to be obtained from the Weather Underground's site.
     */
    private String getCityInfo(String city, String state, String station)
    {
        String cityInfo = null;
        if (city!=null && state !=null && !city.equals("") && !state.equals(""))
        {
            cityInfo = getUSInfo(city, state);
        }
        else if (station != null && !station.equals(""))
        {
            cityInfo = "global/stations/" + station;
        }
        return cityInfo;
    }
    
    /**
     * @see VelocityPortletAction#doCancel
     */    
    public void doCancel(RunData data, Context context)
    {
        VelocityPortlet portlet = (VelocityPortlet) context.get("portlet");
        buildNormalContext(portlet, context, data);
    }
    
    /**
     * Update PSML parmaters to reflect the desired
     * weather station, i.e. city
     *
     * @param data data
     * @param context a context for web pages.
     */
    public void doUpdate(RunData data, Context context)
    {
        String city = (String) data.getParameters().getString("weather_city");
        String state = (String) data.getParameters().getString("weather_state");
        String style = (String) data.getParameters().getString("weather_style");
        String station = (String) data.getParameters().getString("weather_station");
        
        String cityInfo = getCityInfo(city, state, station);
        if (cityInfo != null)
        {
            VelocityPortlet portlet = (VelocityPortlet) context.get("portlet");
            context.put("weather_city_info", cityInfo);
            portlet.setAttribute("weather_city_info", cityInfo, data);
            if (style == null || style.equals(""))
            {
                style = "infobox";
            }
            context.put("weather_style", style);
            portlet.setAttribute("weather_style", style, data);
        }
    }
}

