/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  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 acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS 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 was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

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

package org.bodington.util;

import java.awt.Color;
import java.util.StringTokenizer;

/**
 *
 * @author  administrator
 */
public class ColourPreferenceMapper
{
    public static final int TYPE_NORMAL         = 0;
    public static final int TYPE_SOFT           = 1;
    public static final int TYPE_CONTRAST       = 2;
    public static final int TYPE_BLACK_ON_WHITE = 3;
    public static final int TYPE_WHITE_ON_BLACK = 4;
    
    Color reference_background = Color.white;
    Color reference_foreground = Color.black;
    
    boolean dark_background;
    Color adjusted_background;
    
    
    int type = TYPE_NORMAL;
    boolean valid = false;
    
    /** Creates a new instance of ColourPreferenceMapper */
    public ColourPreferenceMapper()
    {
    }

    public ColourPreferenceMapper( String code )
    {
        if ( code!=null )
        {
            StringTokenizer t = new StringTokenizer( code, "." );
            try
            {
                if ( t.hasMoreTokens() )
                    type = Integer.decode( t.nextToken() ).intValue();
                if ( type<TYPE_NORMAL || type>TYPE_WHITE_ON_BLACK )
                    type = TYPE_NORMAL;
                if ( t.hasMoreTokens() )
                    reference_background =  Color.decode( t.nextToken() );
                if ( t.hasMoreTokens() )
                    reference_foreground =  Color.decode( t.nextToken() );
            }
            catch ( NumberFormatException nfe )
            {
                // just leave properties at default if code is invalid
            }
        }
    }

    public synchronized void setType( int n )
    {
        type = n;
        valid = false;
    }

    public synchronized void setReferenceColours( Color b, Color f )
    {
    reference_background = b;
    reference_foreground = f;
    valid = false;
    }

    public synchronized Color getReferenceBackgroundColor()
    {
        return reference_background;
    }
    
    public synchronized Color getReferenceForegroundColor()
    {
        return reference_foreground;
    }
    
    public synchronized Color getPreferredBackgroundColor()
    {
        if ( !valid )
            readjust();
        
        return adjusted_background;
    }
    
    public synchronized Color getPreferredForegroundColor( Color input )
    {
        if ( !valid )
            readjust();
        
        if ( type == TYPE_NORMAL )
            return input;
        if ( type == TYPE_BLACK_ON_WHITE )
            return Color.black;
        if ( type == TYPE_WHITE_ON_BLACK )
            return Color.white;

        float value_diff;
        float[] col_components_f = new float[3], col_components_b = new float[3];

        Color.RGBtoHSB( 
                adjusted_background.getRed(), 
                adjusted_background.getGreen(), 
                adjusted_background.getBlue(),
                col_components_b );
        Color.RGBtoHSB( 
                input.getRed(), 
                input.getGreen(), 
                input.getBlue(),
                col_components_f );

        value_diff = col_components_f[2] - col_components_b[2];

        if ( type == TYPE_CONTRAST )
        {
            if ( dark_background )
            {
                if ( value_diff < 0.6 )
                    col_components_f[2] = col_components_b[2] + (float)0.6;
            }
            else
            {
                if ( value_diff > -0.6 )
                    col_components_f[2] = col_components_b[2] - (float)0.6;
            }
        }
        
        if ( type == TYPE_SOFT )
        {
            if ( col_components_f[1] > 0.5 )
                col_components_f[1] = (float)0.5;
                
            if ( dark_background )
            {
                if ( value_diff > 0.4 )
                    col_components_f[2] = col_components_b[2] + (float)0.4;
            }
            else
            {
                if ( value_diff < -0.4 )
                    col_components_f[2] = col_components_b[2] - (float)0.4;
            }
        }
        
    return Color.getHSBColor( col_components_f[0], col_components_f[1], col_components_f[2] );        
    }
    
    private synchronized void readjust()
    {
        valid = true;
        
        if ( type == TYPE_NORMAL )
        {
            adjusted_background = reference_background;
            return;
        }
        if ( type == TYPE_BLACK_ON_WHITE  )
        {
            adjusted_background = Color.white;
            return;
        }
        if ( type == TYPE_WHITE_ON_BLACK )
        {
            adjusted_background = Color.black;
            return;
        }

        float value_diff;
        float[] col_components_f = new float[3], col_components_b = new float[3];

        Color.RGBtoHSB( 
                reference_background.getRed(), 
                reference_background.getGreen(), 
                reference_background.getBlue(),
                col_components_b );
        Color.RGBtoHSB( 
                reference_foreground.getRed(), 
                reference_foreground.getGreen(), 
                reference_foreground.getBlue(),
                col_components_f );

        dark_background = col_components_b[2] < col_components_f[2];
        
        // work out if background needs to be adjusted to increase
        // contrast or reduce its colour saturation
        value_diff = col_components_f[2] - col_components_b[2];
        if ( type == TYPE_CONTRAST )
        {
            if ( dark_background )
            {
                if ( (col_components_b[2] + 0.6) <= 1.0 )
                    {
                        adjusted_background = reference_background;
                        return;
                    }
                col_components_b[2] = (float)0.4;
            }
            else
            {
                if ( (col_components_b[2] - 0.6) >= 0.0 )
                    {
                        adjusted_background = reference_background;
                        return;
                    }
                col_components_b[2] = (float)0.6;
            }
        }
        
        if ( type == TYPE_SOFT )
        {
            if ( col_components_b[1] < 0.3 )
            {
                adjusted_background = reference_background;
                return;
            }
                
            // reduce saturated colours
            if ( col_components_b[1] > 0.3 )
                col_components_b[1] = (float)0.3;
        }

        // convert altered colors back to RGB
        adjusted_background = Color.getHSBColor( col_components_b[0], col_components_b[1], col_components_b[2] );
    }
    
    
    /** Creates a string code to represent the content of the instance */
    public String toString()
    {
        StringBuffer code = new StringBuffer();
        code.append( Integer.toHexString( type ) );
        code.append( ".0x" );
        code.append( Integer.toHexString( reference_background.getRGB() & 0xffffff ) );
        code.append( ".0x" );
        code.append( Integer.toHexString( reference_foreground.getRGB() & 0xffffff ) );
        
        return code.toString();
    }
}
