/*
 * Copyright (c) 2011, Patrik Dufresne. All rights reserved.
 * Patrik Dufresne PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.planimod.ui.databinding;

import java.util.Date;

import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

import com.patrikdufresne.jface.databinding.ControlStyleSupport;
import com.patrikdufresne.jface.databinding.ControlStyleUpdater;
import com.patrikdufresne.ui.ColorUtil;

/**
 * 
 * @author Patrik Dufresne
 * 
 */
public class DateColorControlStyleSupport {

	public static ControlStyleSupport create(Control control,
			IObservableValue date) {
		// Create a new Control style updater.
		return ControlStyleSupport.create(control, date,
				new ControlStyleUpdater() {
					/**
					 * Resource id use with color registry.
					 */
					private static final String IN_PAST = "DateColorControlStyleSupport.inPast"; //$NON-NLS-1$
					/**
					 * The color;
					 */
					private Color inPast;

					/**
					 * This implementation update the background color of the
					 * widget based on the status.
					 */
					@Override
					public void update(Control control, Object status) {
						Color background = Display.getDefault().getSystemColor(
								SWT.COLOR_LIST_BACKGROUND);
						if (status instanceof Date
								&& ((Date) status).compareTo(new Date()) < 0) {
							background = getInPastColor();
						}
						control.setBackground(background);
					}

					/**
					 * Return the color.
					 * 
					 * @return
					 */
					private Color getInPastColor() {
						if (this.inPast == null) {
							if (!JFaceResources.getColorRegistry().hasValueFor(
									IN_PAST)) {
								RGB rgb = ColorUtil
										.blend(Display
												.getDefault()
												.getSystemColor(
														SWT.COLOR_LIST_BACKGROUND)
												.getRGB(),
												Display.getDefault()
														.getSystemColor(
																SWT.COLOR_WIDGET_BACKGROUND)
														.getRGB(), 50);
								JFaceResources.getColorRegistry().put(IN_PAST,
										rgb);
							}
							this.inPast = JFaceResources.getColorRegistry()
									.get(IN_PAST);
						}
						return this.inPast;
					}

				});
	}

}
