/*
 * $Id: AbstractServerGraph.java,v 1.3 2007-03-11 20:40:58 larry Exp $ 
 */
package com.representqueens.web.tags.spark;

/*
 * 
 * Copyright 2007 Larry Ogrodnek
 *
 * 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.
 */
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import com.representqueens.util.StringUtils;

/**
 * @author Larry Ogrodnek <larry@cheesesteak.net>
 * @version $Revision: 1.3 $ $Date: 2007-03-11 20:40:58 $
 */
public abstract class AbstractServerGraph extends AbstractGraph
{
  private static final String DEFAULT_PATH = "/spark";
  
  private String path;

  public String getPath()
  {
    return this.path;
  }

  public void setPath(final String path)
  {
    this.path = path;
  }
  
  public String getRealPath()
  {
    final Object o = this.pageContext.findAttribute("sparkPath");
    
    if (o instanceof String)
    {
      return convertPath(o.toString());
    }
    
    return convertPath((this.path == null ? DEFAULT_PATH : this.path));
  }
  
  private String convertPath(final String s)
  {
    final String c = ((HttpServletRequest) this.pageContext.getRequest()).getContextPath();
    return String.format("%s%s", c, s);
  }

  protected String getQueryParams()
  {
    final StringBuilder sb = new StringBuilder();
    
    final String[] n = new String[] { "color", "highcolor", "lastcolor", "background", "width", "height", "spacing", "output" };
    final String[] p = new String[] { getColor(), getHighColor(), getLastColor(), getBackground(), getWidth(), getHeight(), getSpacing(), getOutput() };
    
    try
    {
      for (int i = 0; i < n.length; i++)
      {
        if (!StringUtils.isEmpty(p[i]))
        {
          sb.append("&").append(n[i]).append("=").append(URLEncoder.encode(p[i], "UTF-8"));
        }
      }
    }
    catch (final UnsupportedEncodingException uee)
    {
      // won't happen...
    }
    
    
    final Number[] data = getData();
    
    if (data != null && data.length > 0)
    {
      sb.append("&data=");
      sb.append(StringUtils.toString(data));
    }
    
    return sb.toString();
  }  
}
