import java.io.*;

public class PageGenerator
{
  public String title;
  
  public PageGenerator( String title )
  {
    this.title = title;
  }
  
  public void writePage( String filename )
  {
    String fullFilename = FileChooser.getMediaPath( filename+".html" );
    try {
      BufferedWriter output = new BufferedWriter(
                                  new FileWriter(fullFilename) );
      this.writePreamble( output );
      this.writeHeader( output );
      this.writeBody( output );
      this.writePostamble( output );
      output.close();
    } catch (IOException ex) {
      System.out.println( "An error occurred reading the file " + filename );
    }
  }
  
  // ----- standard helpers
  
  private void writePreamble( BufferedWriter output ) throws IOException
  {
    output.write( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD " +
                  "HTML 4.01 Transition //EN\">" );
    output.newLine();
    output.write( "<HTML>" );
    output.newLine();
  }
  
  private void writeHeader( BufferedWriter output ) throws IOException
  {
    output.write( "<HEAD>" );
    output.newLine();
    output.write( "<TITLE>" );
    output.newLine();
    output.write( title );
    output.newLine();
    output.write( "</TITLE>" );
    output.newLine();
    output.write( "</HEAD>" );
    output.newLine();
  }
  
  private void writePostamble( BufferedWriter output ) throws IOException
  {
    output.write( "</HTML>" );
    output.newLine();
  }
  
  // ----- customized helpers
  
  private void writeBody( BufferedWriter output ) throws IOException
  {
    output.write( "<BODY>" );
    output.newLine();
    
    this.writeComic( output );
    this.writeQuote( output );
    
    output.write( "</BODY>" );
    output.newLine();
  }
  
  private void writeComic( BufferedWriter output ) throws IOException
  {
    FoxTrotDownloader comicReader = new FoxTrotDownloader();
    String comicFilename = comicReader.getTodaysCartoon();
    
    output.write( "<H1> Today's FoxTrot </H1>" );
    output.newLine();
    output.write( "<CENTER>" );
    output.newLine();
    output.write( "<IMG SRC=\"" + comicFilename + "\" " +
                  "     ALT=\"" + comicFilename + "\"/>" );
    output.newLine();
    output.write( "</CENTER>" );
    output.newLine();
  }
  
  private void writeQuote( BufferedWriter output ) throws IOException
  {
    QuoteFileReader quoteReader = new QuoteFileReader();
    quoteReader.loadQuotes( FileChooser.getMediaPath("quotes-sample.txt") );
    String quote = quoteReader.getRandomQuote();
    
    output.write( "<H1> Today's Random Thought </H1>" );
    output.newLine();
    output.write( "<P>" );
    output.newLine();
    output.write( quote );
    output.newLine();
    output.write( "</P>" );
    output.newLine();
  }
}
