/*
 * WebWork, Web Application Framework
 *
 * Distributable under Apache license.
 * See terms of license at opensource.org
 */
package com.BookList.action;

import webwork.action.ActionSupport;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 *   A list of books
 *
 *  @webwork:action name="bookList"
 *
 *   @see <related>
 *   @author Rickard Öberg (<email>)
 *   @version $Revision: 1.4 $
 */
public class BookList
   extends ActionSupport
{
   // Attributes ----------------------------------------------------
   static List books;
   
   static
   {
      // This never changes, so we do it once only
      books = new ArrayList();
      
      class Book
      {
         String title;
         String author;
         String publisher;
   
         public String getTitle()
         {
            return title;
         }
   
         public void setTitle(String title)
         {
            this.title = title;
         }
   
         public String getAuthor()
         {
            return author;
         }
   
         public void setAuthor(String author)
         {
            this.author = author;
         }
   
         public String getPublisher()
         {
            return publisher;
         }
   
         public void setPublisher(String publisher)
         {
            this.publisher = publisher;
         }
      }
      
      // We read the values from a file so that it is easy to change
      try
      {
         InputStream resource = BookList.class.getResourceAsStream("books.txt");
         BufferedReader in = new BufferedReader(new InputStreamReader(resource));
         String bookInfo;
         while ((bookInfo = in.readLine()) != null)
         {
            StringTokenizer tokens = new StringTokenizer(bookInfo, ",");
            Book book = new Book();
            book.setTitle(tokens.nextToken());
            book.setAuthor(tokens.nextToken());
            book.setPublisher(tokens.nextToken());
            books.add(book);
         }
         in.close();   
      } catch (Throwable e)
      {
         e.printStackTrace(System.err);
         System.err.println("Could not read list of books");
      }
   }
   
   // Public --------------------------------------------------------
   public List getBooks()
   {
      return books;
   }

   public Object[] getBookArray()
   {
      return books.toArray();
   }
}
