001package edu.pdx.cs410J.grader;
002
003import java.io.PrintWriter;
004import java.io.Writer;
005import java.util.ArrayDeque;
006import java.util.Deque;
007
008public class HtmlGenerator {
009  public static final String DOC_TYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">";
010  private static final String TEXT = "___TEXT___";
011
012  private final PrintWriter writer;
013  private final Deque<String> openTags;
014
015  public HtmlGenerator(Writer writer) {
016    this.openTags = new ArrayDeque<>();
017
018    this.writer = new PrintWriter(writer, true);
019    this.writer.print(DOC_TYPE);
020  }
021
022  public void beginTag(String tagName) {
023    indent();
024    this.writer.print("<" + tagName + ">");
025    this.openTags.push(tagName);
026  }
027
028  private void indent() {
029    this.writer.print("\n");
030    int indent = this.openTags.size() * 2;
031    for (int i = 0; i < indent; i++) {
032      this.writer.print(" ");
033    }
034
035  }
036
037  public void endTag() {
038    String openTag = this.openTags.pop();
039    if (TEXT.equals(openTag)) {
040      openTag = this.openTags.pop();
041
042    } else {
043      indent();
044    }
045    this.writer.print("</" + openTag + ">");
046    this.writer.flush();
047  }
048
049  public void text(String text) {
050    this.openTags.push(TEXT);
051    this.writer.print(text);
052  }
053}