/**
 * Class that stores text along with a color in which to display it. Optionally
 * supports spell-checking the word or not allowing Qs in it.
 */
class StyledWord {
  private StringBuffer text = new StringBuffer();
  private Color color = new Color("black");
  private String url;  // text will link to this url

  private Spellchecker spellchecker = null;
  private LinkUpdater linkUpdater = null;

  public StyledWord() {
  }

  public StyledWord(Spellchecker c) { 
    spellchecker = c;
  }

  public StyledWord(LinkUpdater u) { 
    linkUpdater = u;
  }

  public StyledWord(Spellchecker c, LinkUpdater u) { 
    spellchecker = c;
    linkUpdater = u;
  }

  public Color getColor() {
    return color;
  }

  public void setColor(Color c) {
    color = c;
  }

  public String getLink() {
    return url;
  }

  public void setLink(String url) {
    this.url = url;
  }

  public String getText() {
    return new String(text);
  }

  public void addLetter(char c, int position) { 
    text.insert(position, c); 
    afterWordChange();
  }

  public void deleteLetter(int position) { 
    text.delete(position, position+1); 
    afterWordChange();
  }

  private void afterWordChange() {
    if (spellchecker != null) {
      spellchecker.performSpellcheck(this);
    }
    if (linkUpdater != null) {
      linkUpdater.updateLink(this);
    }
  }
}

/** Makes text that looks like a URL into a link. */
class LinkUpdater {
  public void updateLink(StyledWord word) {
    String text = word.getText();
    word.setLink(text.startsWith("http://") ? text : null);
  }
}

/** Changes the color of a word to red if it isn't found in the dictionary. */
class Spellchecker {
  private Dictionary dictionary;

  public Spellchecker(String language) {
    dictionary = Dictionary.findDictionary(language);
  }

  public void performSpellcheck(StyledWord word) {
    if (dictionary.contains(word.getText())) {
      word.setColor(new Color("black"));
    } else {
      word.setColor(new Color("red"));
    }
  }
}