/*
 * DocumentMediator.java  $Revision: 1.2 $  $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 javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import com.meldcraft.application.ApplicationContext;
import com.meldcraft.application.ApplicationContextEvent;
import com.meldcraft.application.ApplicationContextListener;

/**
 * @version $Revision: 1.2 $ $Date: 2007/10/03 04:39:39 $
 * @author Rob Richards
 */
public class DocumentMediator extends DocumentEmitter implements ApplicationContextListener
{
    public DocumentMediator(ApplicationContext context, String elementId, Document document)
    {
        super(context, elementId, document);
        context.addApplicationContextListener(this, elementId + ".documentChanged");
    }

    public void applicationContextChanged(ApplicationContextEvent e)
    {
        Object newVal = e.getValue();
        try
        {
            String curVal = mDocument.getText(0, mDocument.getLength());
            if (newVal != curVal)
            {
                if (newVal == null)
                {
                    mDocument.remove(0, mDocument.getLength());
                }
                else
                {
                    String str = String.valueOf(newVal);
                    mDocument.remove(0, mDocument.getLength());
                    mDocument.insertString(0, str, null);
                }
            }
        }
        catch (BadLocationException ex)
        {
            // TODO
        }
        catch (IllegalStateException ex)
        {
            String msg = ex.getMessage();
            if ((msg == null) || (msg.indexOf("Attempt to mutate in notification") == -1))
            {
                throw ex;
            }
        }
    }
}



