/**
 * Copyright (c) 2011, Martin Foster <martin@ethereal-realms.org>
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice, 
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the 
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Ethereal-Realms.org nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.lyra.Widgets;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * A method for preventing unwanted information from making its way into past
 * the initial user interface.  This will permit ports to remain numeric, 
 * domains to match a specific structure and so forth.
 * <p>
 * An example for the use of this document constraint is as follows:
 * <code>
 * RegexConstrainedDocument doc = new RegexConstrainedDocument("^[\\w-. ]{0,45}$");
 * JTextField fieldName = new JTextField(doc, "", 45);
 * </code>
 * As shown above a new constraint document will be created enforcing with length
 * of the string allowed as well as the characters supported.  In this case 
 * [A-Z],[a-z],[0-9],[space],[.],[-] are the characters that will be allowed for
 * this filter.
 * <p>
 * @author Martin Foster
 * @version 1.0.4, %Revision, 99%, %LastChangedDate, 17/03/11 8:17PM%
 */
public class RegexConstrainedDocument extends PlainDocument {

	// Serial dreams
	private static final long serialVersionUID = 1L;
	
	// Regular expression components
	private Pattern myPattern;
    private Matcher myMatch;
    
    /**
     * Most basic constructor for the class.  Using this element will result
     * in a working document but will not permit changes due to the fact that
     * no Regular Expression has been attached.
     */
    public RegexConstrainedDocument () { super(); }

    
    /**
     * Constructor which can provide a document to create the initial 
     * data set.  Like the most basic constructor Regular Expressions will not
     * be enabled.
     * <p>
     * @param c Content of an existing document to make use of here.
     */
    public RegexConstrainedDocument (AbstractDocument.Content c) { super(c); }

    
    /**
     * Constructor which can provide a document to create the initial data set
     * for the document.  Will also initialise the Regular Expression meaning
     * the the document may be blanked if the verification fails.
     * <p>
     * @param c Content of an existing document to make use of here.
     * @param p String containing regular expression pattern.
     */
    public RegexConstrainedDocument (AbstractDocument.Content c, String p) {
    	// Let the super class do its work
        super(c);
        
        // Enable the Regular Expression and determine match
        setPatternByString(p);
    }
    // End of Constructor Method
    
    
    /**
     * Constructor to create an empty document with an associated pattern.  If the
     * pattern is too strict you may not be able to proceed since it will never
     * match.
     * <p>
     * @param p String containing regular expression pattern.
     */
    public RegexConstrainedDocument (String p) {
    	// Let the super class do its work
        super();
        
        // Enable the Regular Expression and determine match
        setPatternByString(p);
    }
    // End of Constructor Method

        
    /**
     * Method used to inject a regular expression into the Constrained Document
     * which will also confirm that the document currently matches that data
     * set.  Otherwise it will blank the document.
     * <p>
     * @param p String containing regular expression pattern.
     */
    public void setPatternByString (String p) {
    	
    	// Compile the new pattern
        Pattern pattern = Pattern.compile(p);
        
        
        /*
         * Check the document against the new pattern and removes the content
         * if it no longer matches.
         */  
        try {
        	// Create a match
            myMatch = pattern.matcher (getText(0, getLength()));

            // Reset document if the match failed
            if (!myMatch.matches())
                remove(0, getLength());

        } 
        
        // We quietly ignore this as this should never happen
        catch (BadLocationException ble) {}
    }
    // End of setPatternByString

    
    /**
     * Returns the current pattern.  This could realistically be blanked since
     * it is possible to create a document without specifying a document.
     * <p>
     * @return String containing pattern
     */
    public Pattern getPattern() { 
    	
    	// Straight through pass
    	return myPattern; 
    }
    // End of getPattern Method

    
    /* (non-Javadoc)
     * @see javax.swing.text.PlainDocument#insertString(int, java.lang.String, javax.swing.text.AttributeSet)
     */
    public void insertString (int offs, String s, AttributeSet a) throws BadLocationException {
        
    	
    	/*
    	 * Build up the string as it should be passed onto the Super class and
    	 * run our own checks.
    	 */
        String proposedInsert =
            getText (0, offs) +
            s +
            getText (offs, getLength() - offs);

        /*
         * Now we run the matcher against the proposed string.  If there is a
         * match we pass it onto the Super class, otherwise we silently pass by
         * making the change invalid.
         */
        if (myMatch != null) {
        	
        	// Matcher has been used previously so reset
            myMatch.reset(proposedInsert);

            // Silently return
            if (! myMatch.matches())
                return;
        }
        
        // Pass onto Super class
        super.insertString(offs, s, a);
    }
    // End of insertString Method

}
