/*
 * 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 MaskatComboBoxPropertyDescriptor extends
		ComboBoxPropertyDescriptor {
	
	private String[] labels;
	
    private class TextLabelProvider extends LabelProvider {
        public String getText(Object element) {
        	return element.toString();
        }
    }
    
    private class TextComboBoxCellEditor extends ComboBoxCellEditor {
		public TextComboBoxCellEditor(Composite parent, String[] items, int style) {
			super(parent, items, style);
		}

		protected void doSetValue(Object value) {
			super.doSetValue(new Integer(indexOfLabel(value.toString())));
		}
		
		protected Object doGetValue() {
			Object value = super.doGetValue();
    		int index = value instanceof Integer ? ((Integer)value).intValue() : -1;
    		if (index<0 || index >= labels.length)
    			return "";
    		return labels[index];
		}
		
    }
	
	public MaskatComboBoxPropertyDescriptor(Object id, String displayName, String[]labels) {
		super(id, displayName, labels);
		this.labels = labels;
		setLabelProvider(new TextLabelProvider());
		setCategory(Category.getCategory(displayName));
	}
	
	public CellEditor createPropertyEditor(Composite parent) {
		CellEditor editor = new TextComboBoxCellEditor(parent, labels, SWT.READ_ONLY);
	    if (getValidator() != null) {
			editor.setValidator(getValidator());
		}
	    return editor;
	}
	
    private int indexOfLabel(String item) {
    	for (int i=0; i<labels.length && item != null; i++) {
    		if (item.equals(labels[i])) {
    			return i;
    		}
    	}
    	return -1;
    }

}
