/*
 * ActionEmitter.java  $Revision: 1.5 $  $Date: 2007/10/03 04:39:39 $
 *
 * Copyright (C) 2007 Meldcraft Corporation
 *
 * This file is part of Scaffold.
 * 
 * Scaffold is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Scaffold is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with Scaffold.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.meldcraft.application.guis.mvc;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;

import javax.swing.text.JTextComponent;

import com.meldcraft.application.ApplicationContext;
import com.meldcraft.application.util.BeanUtil;
import com.meldcraft.util.PropertiesHelper;
import com.meldcraft.util.ReflectUtil;

/**
 * @version $Revision: 1.5 $ $Date: 2007/10/03 04:39:39 $
 * @author Rob Richards
 */
public class ActionEmitter implements ActionListener
{
    private ApplicationContext  mContext;
    private String              mElementId;
    protected String            mActionProperty;
    protected String            mSuffix = ".actionPerformed";

    public ActionEmitter(ApplicationContext context, String elementId, Component comp)
    {
        mContext = context;
        mElementId = elementId;
        String def = (comp instanceof JTextComponent) ? "text" : "value";
        mActionProperty = PropertiesHelper.getString(context.getConfiguration(), elementId + ".actionProperty", def);
        if (comp instanceof JTextComponent)
        {
            mSuffix = ".documentChanged";
        }

        try
        {
            ReflectUtil.invokeMethod(comp, "addActionListener", this);
        }
        catch (NoSuchMethodException e)
        {
        }
        catch (IllegalAccessException e)
        {
        }
        catch (InvocationTargetException e)
        {
        }
    }

    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();
        Object val = BeanUtil.getPropertyValue(source, mActionProperty);
        mContext.contextChanged(mElementId + mSuffix, val);
    }
}



