// MapResource.java
// $Id: MapResource.java,v 1.6 1998/02/26 13:20:02 bmahe Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package org.w3c.jigsaw.map ;

import java.net.* ;
import java.util.*;
import java.io.*;

import org.w3c.tools.resources.*;

/**
 * Implements handling of image map requests.  Understands both the
 * NCSA and the W3C (CERN) format for map description files, with
 * the "nosearch" extension for both.
 *
 * @author <a href="mailto:anto@w3.org">Antonio Ram&iacute;rez</a>
 */
 
public class MapResource extends FileResource {

  // Attribute for internal representation of map data:
  protected static int ATTR_MAP = -1;

  // NCSA/W3C map file format flag
  protected static int ATTR_NCSA = -1;
    
  static {
    Attribute a = null;
    Class cls = null;
    try {
      cls = Class.forName("org.w3c.jigsaw.map.MapResource") ;
    } catch (Exception ex) {
      ex.printStackTrace();
      System.exit(0);
    }

    a = new MapAttribute("map"
			 , null
			 , Attribute.COMPUTED) ;
    ATTR_MAP = AttributeRegistry.registerAttribute(cls,a);

    a = new BooleanAttribute("useNCSA"
			     , Boolean.FALSE
			     , Attribute.EDITABLE);
    ATTR_NCSA = AttributeRegistry.registerAttribute(cls,a);
  }

  // Hopefully this will make the MapAttribute persistent

  /**
   * This method parses the map file whenever it changes.
   */
  public void updateFileAttributes()
  {

    super.updateFileAttributes();

    Map map = null;

    try {
      map = parseMap();
    } catch(IOException ex) {
      map = null;
    } catch(MapException ex) {
      map = null;
    } finally {
      setValue(ATTR_MAP, map);
    }
  }

  public Map getMap() 
    throws IOException, MapException
  {
    Map map = (Map) getValue(ATTR_MAP,null);
    if (map == null) {
      map = parseMap();
      setValue(ATTR_MAP,map) ;
    }
    return map;
  }

  private boolean getUseNCSA()
  {
    return ((Boolean)
	    getValue(ATTR_NCSA,Boolean.FALSE)).booleanValue();
  }

  // Parse the map freshly from file 
  private final Map parseMap()
    throws IOException, MapException
  {
    return new Map(new
		   DataInputStream(new
				   FileInputStream(getFile())),
		   getUseNCSA());
  }

  public void initialize(Object values[]) {
    super.initialize(values);
    try {
      registerFrameIfNone("org.w3c.jigsaw.map.MapFrame",
			  "map-frame");
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}
