package com.ht.ui.property;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import javafx.beans.property.SimpleStringProperty;

public class SimpleBeanStringProperty extends SimpleStringProperty {

	public SimpleBeanStringProperty(Object bean, String name) {
		super(bean, name);
		if (bean != null && name != null && !name.isEmpty()) {
			
			Object obj = null;
			try {

				String method = "get" + name.substring(0, 1).toUpperCase()
						+ name.substring(1);
				obj = bean.getClass().getMethod(method, new Class[] {})
						.invoke(bean);
				
			} catch (IllegalArgumentException e) {
//				e.printStackTrace();
			} catch (SecurityException e) {
//				e.printStackTrace();
			} catch (IllegalAccessException e) {
//				e.printStackTrace();
			} catch (InvocationTargetException e) {
//				e.printStackTrace();
			} catch (NoSuchMethodException e) {
//				e.printStackTrace();
			} finally {
				
				if (obj != null) {
					super.set((String) obj);
				} else {
					super.set("");
				}
			}
		}
	}

	private void setBeanProperty(Object value) {

		if (getBean() != null && !getName().isEmpty()) {
			if(value == null) {
				value = "";
			}
			try {
				Field field = getBean().getClass().getDeclaredField(getName());

				String method = "set" + getName().substring(0, 1).toUpperCase()
						+ getName().substring(1);
				getBean().getClass()
						.getMethod(method, new Class[] { field.getType() })
						.invoke(getBean(), new Object[]{value});

			} catch (IllegalArgumentException e) {
//				e.printStackTrace();
			} catch (SecurityException e) {
//				e.printStackTrace();
			} catch (NoSuchFieldException e) {
//				e.printStackTrace();
			} catch (NoSuchMethodException e) {
//				e.printStackTrace();
			} catch (IllegalAccessException e) {
//				e.printStackTrace();
			} catch (InvocationTargetException e) {
//				e.printStackTrace();
			}
		}
	}

	@Override
	public void set(String v) {
		setBeanProperty(v);
		super.set(v);
	}

	@Override
	public void setValue(String v) {
		setBeanProperty(v);
		super.setValue(v);
	}

}
