/*===========================================================================
 *
 * File:	MorrowMapArray.JAVA
 * Author:	Dave Humphrey (uesp@m0use.net)
 * Created On:	Monday, August 27, 2001
 *
 * Implements an array of TamMapRecord objects from a map database.
 *
 *=========================================================================*/

	/* Import Packages */
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import java.util.Vector;
import MorrowMapRecord;
import MorrowMapOptions;
import MorrowMapLocTypes;


/*===========================================================================
 *
 * Begin Class MorrowMapArray
 *
 *=========================================================================*/
public class MorrowMapArray  {

  /*---------- Begin Class Data Members --------------------------*/

  Vector m_MapArray;	/* Holds the array of map record objects */

  String m_FileBuffer;	/* File buffer used when loading file */

  /*---------- End of Class Data Members -------------------------*/


/*===========================================================================
 *
 * Constructor - public MorrowMapArray ();
 *
 *=========================================================================*/
public MorrowMapArray () {
  m_MapArray = new Vector();
  m_FileBuffer = new String();
 }
/*===========================================================================
 *		End of Constructor MorrowMapArray()
 *=========================================================================*/


/*===========================================================================
 *
 * Method - public int CreateImage (graph, MapOptions);
 *
 * Outputs the locations to the given graphics object using the given map 
 * options.
 *
 *=========================================================================*/
public int CreateImage (Graphics graph, MorrowMapOptions MapOptions) {
  MorrowMapRecord MapRecord;
  int	          Index;

  //System.out.println ("MapArray::CreateImage...start, 0..." + m_MapArray.size());

	/* Output each element in array */
  for (Index = 0; Index < m_MapArray.size(); Index++) {
    //System.out.println("Outputting object " + Index);
    MapRecord = (MorrowMapRecord) m_MapArray.elementAt(Index);
    MapRecord.OutputImage(graph, MapOptions);
   }
  
  //System.out.println ("MapArray::CreateImage...end");
  return (0);
 }
/*===========================================================================
 *		End of Method CreateImage()
 *=========================================================================*/


/*===========================================================================
 *
 * Function - public void DebugOutput ();
 *
 * Outputs debug information to the system.out stream.
 *
 *=========================================================================*/
public void DebugOutput () {
  System.out.println("Debug output...");
  System.out.println("\tm_FileBuffer Length = " + m_FileBuffer.length());
  System.out.println("\tm_MapArray Size = " + m_MapArray.size());

  if (m_MapArray.size() > 0) {
    MorrowMapRecord MapRecord = (MorrowMapRecord) m_MapArray.elementAt(0);
    System.out.println("Debug output element 0...");
    MapRecord.DebugOutput();

    if (m_MapArray.size() > 1) {
      MapRecord = (MorrowMapRecord) m_MapArray.elementAt(m_MapArray.size()-1);
      System.out.println("Debug output last element... ");
      MapRecord.DebugOutput();
     }
   }

 }
/*===========================================================================
 *		End of Function void DebugOutput()
 *=========================================================================*/


/*===========================================================================
 *
 * Method - int LoadDatabase (DatabaseFileUrl, IsLandmark);
 *
 * Attempts to load/parse the database from the given URL address.  Returns
 * 0 on success or -1 or any error.
 *
 *=========================================================================*/
public int LoadDatabase (String DatabaseFileUrl, boolean IsLandmark) {
  int Result;

	/* Clear the current array contents */
  m_MapArray.removeAllElements();

	/* Read and parse database file */
  Result = ReadDatabase(DatabaseFileUrl);
  if (Result >= 0) Result = ParseDatabase(IsLandmark);

  return (Result);
 }
/*===========================================================================
 *		End of Method LoadDatabase()
 *=========================================================================*/


/*===========================================================================
 *
 * Class MorrowMap Method - int ParseDatabase (IsLandmark);
 *
 * Parses a map database string into the its appropiate map record array from
 * the current file buffer. Returns 0 on success or -1 on any error.
 *
 *=========================================================================*/
int ParseDatabase (boolean IsLandmark) {
  MorrowMapRecord  MapRecord = new MorrowMapRecord();
  String	InputLine;
  int           StartIndex = 0;
  int		CharIndex;
  int		Result;
  boolean       ReadingLocation = false;

	/* Parse the file line by line */
  do {
		/* Find the end of the next line */
    CharIndex = m_FileBuffer.indexOf('\n', StartIndex);
    //System.out.println("\tFound line at " + CharIndex);

		/* Special case for end of file */
    if (CharIndex < 0) 
      InputLine = m_FileBuffer.substring(StartIndex);
    else
      InputLine = m_FileBuffer.substring(StartIndex, CharIndex);

		/* Check for start of a location record */
    if (InputLine.equals("loc")) {
      MapRecord.DestroyContents();
      ReadingLocation = true;
     }
		/* Parse a location record line */
    else if (ReadingLocation) {
      Result = MapRecord.ParseTextLine(InputLine);

		/* Check for the end of a location record */
      if (Result == MorrowMapRecord.TM_READ_END) {
        ReadingLocation = false;
	MapRecord.IsLandmark = IsLandmark;
	m_MapArray.addElement(MapRecord);
	MapRecord = new MorrowMapRecord();
       }
     }

    StartIndex = CharIndex + 1;
   } while (CharIndex > 0);

	/* Clear the file buffer contents */
  m_FileBuffer = "";
  return (0);
 }
/*===========================================================================
 *		End of Class MorrowMap Method ParseDatabase()
 *=========================================================================*/


/*===========================================================================
 *
 * Class MorrowMap Method - int ReadDatabase (DatabaseFileUrl);
 *
 * Attempts to read the map database from the specific URL address.  The 
 * result is stored in the class member string FileBuffer.  Returns 0 on 
 * success or -1 on any error.
 *
 *=========================================================================*/
int ReadDatabase (String DatabaseFileUrl) {
  URL		theURL;
  URLConnection Connection;
  String	InputLine;
  byte          InputBytes[] = new byte[1024];
  int		Result;
  int		NumBytes;

	/* Clear the contents of the current file buffer */
  m_FileBuffer = "";
  
  	/* Attempt to initialize the URL and data IO streams */
  try {	
    theURL = new URL(DatabaseFileUrl);
   }
	/* Catch an invalid URL address */
  catch (MalformedURLException except) {
    System.out.println("Bad Tamriel Map URL '" + DatabaseFileUrl + "'!");
    return (-1);
   }

	/* Open an URL connection and read file */
  try {
    Connection = theURL.openConnection();
    BufferedInputStream BufferStream = new BufferedInputStream(Connection.getInputStream(), 2048);

		/* Read file 1kb at a time */
    while (true) {
      NumBytes = BufferStream.read(InputBytes, 0, 1024);
      if (NumBytes == -1) break;
      InputLine = new String(InputBytes, 0, NumBytes);
      m_FileBuffer += InputLine;
     }

		/* Debug output */
    System.out.println("\tURL = " + theURL.getFile());
    System.out.println("\tType = " + Connection.getContentType());
    System.out.println("\tSize = " + Connection.getContentLength());
    System.out.println("\tBufferSize = " + m_FileBuffer.length());
   }
	/* Trap any IO errors */
  catch (IOException except) {
    System.out.println("IO Error: " + except.getMessage());
    return (-1);
   }

  return (0);
 }
/*===========================================================================
 *		End of Class MorrowMap Method ReadDatabase()
 *=========================================================================*/

 }
/*===========================================================================
 *		End of Class MorrowMapArray
 *=========================================================================*/


/*===========================================================================
 *		End of File MorrowMapArray.JAVA
 *=========================================================================*/