/*
 * $Id: ColorUtils.java,v 1.2 2006/07/17 20:22:40 larry Exp $ 
 */
package com.representqueens.util;

/*
 * 
 * Copyright 2006 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.awt.Color;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Utility methods for parsing Strings into Color Objects.
 * 
 * @author Larry Ogrodnek <larry@cheesesteak.net>
 * @version $Revision: 1.2 $ $Date: 2006/07/17 20:22:40 $
 */
public final class ColorUtils
{
  private ColorUtils() { }
  
  /**
   * Parse a String into a Color.
   * 
   * This method will accept either a color name (a field name from {@link Color},
   * case insensitive e.g. "red"), or a HTML hex color string (e.g. "#ff0000"
   * for Color.RED).
   * 
   * @param s String to parse for color name or color number.
   * @return Color for s.
   */
  public static Color parseColor(final String s)
  {
    Color color = null;
    
    if (! StringUtils.isEmpty(s))
    {
      try
      {
        color = Color.decode(s);
      }
      catch (final NumberFormatException nfe)
      {
        color = colorByField(s);
      }
    }
    
    return color;
  }
  
  private static Color colorByField(final String _s)
  {
    final Field[] fields = Color.class.getFields();

    final String s = _s.toLowerCase();

    try
    {
      for (final Field f : fields)
      {
        if (f.getName().toLowerCase().equals(s))
        {
          final int mod = f.getModifiers();
          if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Color.class.equals(f.getType()))
          {
            return (Color) f.get(null);
          }
        }
      }
    }
    catch (final IllegalAccessException iae)
    {
      // ?
    }

    return null;
  }
}
