/**
 * The MIT License
 * Copyright © 2026 Luis Andrés Lange <https://javacomm.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.nexuswob.gui;

import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;



/**
 * {@link UrlDocumentFilter} lässt nur gültige URL-Zeichen zu. Alle anderen
 * Zeichen werden während der Eingabe geblockt.
 */
public class UrlDocumentFilter extends DocumentFilter {

  private static final String REGEX = "^[a-zA-Z0-9\\-._~:/?#\\[\\]@!$&'()*+,;=%]*$";

  @Override
  public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
      throws BadLocationException {

    if (string == null) {
      return;
    }

    String newText = buildNewText(fb, offset, 0, string);

    if (newText.matches(REGEX)) {
      super.insertString(fb, offset, string, attr);
    }
    else {
      Toolkit.getDefaultToolkit().beep();
    }
  }



  @Override
  public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
      throws BadLocationException {

    String newText = buildNewText(fb, offset, length, text);

    if (newText.matches(REGEX)) {
      super.replace(fb, offset, length, text, attrs);
    }
    else {
      Toolkit.getDefaultToolkit().beep();
    }
  }



  private String buildNewText(FilterBypass fb, int offset, int length, String text)
      throws BadLocationException {

    String current = fb.getDocument().getText(0, fb.getDocument().getLength());

    return new StringBuilder(current).replace(offset, offset + length, text == null ? "" : text).toString();
  }
}