/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.views.properties.descriptor;


import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.views.properties.ComboBoxPropertyDescriptor;


public class BooleanComboBoxPropertyDescriptor extends
		ComboBoxPropertyDescriptor {
	
	private static String FALSE = "false";
	
	private static String TRUE = "true";
	
	private static String[] labels = new String[]{FALSE, TRUE}; 

    private static class BooleanLabelProvider extends LabelProvider {
        public String getText(Object element) {
            return element.toString();
        }
    }
    
    private static class BooleanComboBoxCellEditor extends ComboBoxCellEditor {
		public BooleanComboBoxCellEditor(Composite parent, String[] items, int style) {
			super(parent, items, style);
		}

		protected void doSetValue(Object value) {
			if (TRUE.equals(value)) {
				//set to "true";
				value = new Integer(indexOfLabel(TRUE));
			} else {
				//set to "false";
				value = new Integer(indexOfLabel(FALSE));
			}
			super.doSetValue(value);
		}
	}
    
    private static int indexOfLabel(String item) {
    	for (int i=0; i<labels.length; i++) {
    		if (item.equals(labels[i])) {
    			return i;
    		}
    	}
    	return -1;
    }
	
	public BooleanComboBoxPropertyDescriptor(Object id, String displayName) {
		super(id, displayName, labels);
		setLabelProvider(new BooleanLabelProvider());
		setCategory(Category.getCategory(displayName));
	}
	
	public CellEditor createPropertyEditor(Composite parent) {
		CellEditor editor = new BooleanComboBoxCellEditor(parent, labels,
	            SWT.READ_ONLY);
	    if (getValidator() != null) {
			editor.setValidator(getValidator());
		}
	    return editor;
	}
}
