/*
 * HyperlinkEmitter.java  $Revision: 1.3 $  $Date: 2007/10/03 04:59:32 $
 *
 * 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.lang.reflect.InvocationTargetException;

import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.event.HyperlinkEvent.EventType;

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

/**
 * @version $Revision: 1.3 $ $Date: 2007/10/03 04:59:32 $
 * @author Rob Richards
 */
public class HyperlinkEmitter implements HyperlinkListener
{
    private ApplicationContext  mContext;
    private String              mElementId;
    private EventType           mEventType;
    protected String            mEventKey;

    public HyperlinkEmitter(ApplicationContext context, String elementId, String eventType, Component comp)
    {
        mContext = context;
        mElementId = elementId;
        mEventType = EventType.ACTIVATED;

        if (eventType != null)
        {
            eventType = eventType.toLowerCase();
            if (eventType.indexOf("entered") != -1)
            {
                mEventType = EventType.ENTERED;
            }
            else if (eventType.indexOf("exited") != -1)
            {
                mEventType = EventType.EXITED;
            }
        }

        String str = mEventType.toString();
        str = str.substring(0,1) + str.substring(1, str.length()).toLowerCase();
        mEventKey = mElementId + ".hyperlink" + str;

        try
        {
            ReflectUtil.invokeMethod(comp, "addHyperlinkListener", this);
        }
        catch (NoSuchMethodException e)
        {
            throw new RuntimeException("Could not addHyperlinkListener", e);
        }
        catch (IllegalAccessException e)
        {
            throw new RuntimeException("Could not addHyperlinkListener", e);
        }
        catch (InvocationTargetException e)
        {
            throw new RuntimeException("Could not addHyperlinkListener", e);
        }
    }

    public void hyperlinkUpdate(HyperlinkEvent e)
    {
        if (mEventType == e.getEventType())
        {
            mContext.contextChanged(mEventKey, e.getURL());
        }
    }
}



