package baf.sci;

import java.io.*;
import java.awt.*;

public class Resource {
  public static final int VIEW    = 0x00;
  public static final int PIC     = 0x01;
  public static final int SCRIPT  = 0x02;
  public static final int TEXT    = 0x03;
  public static final int SOUND   = 0x04;
  public static final int MEMORY  = 0x05;
  public static final int VOCAB   = 0x06;
  public static final int FONT    = 0x07;
  public static final int CURSOR  = 0x08;
  public static final int PATCH   = 0x09;
  public static final int BITMAP  = 0x0a;
  public static final int PALETTE = 0x0b;

  public static final String typenames[] = {
    "view", "pic", "script", "text", "sound", "memory", "vocab", "font",
    "cursor", "patch", "bitmap", "palette" };

  byte b[];
  int restype, resnum;

  public Resource(byte b[], int restype, int resnum) {
    this.b = b;
    this.restype = restype;
    this.resnum = resnum;
  }

  final int getWord(int address) {
    return (b[address+1] << 8) | (b[address] & 0xff);
  }

  final void putWord(int address, int value) {
    b[address] = (byte)value;
    b[address+1] = (byte)(value >> 8);
  }

  public final static int getID(int type, int num) {
    return (type << 0xb) | num;
  }

  public final static int getID(String type, int num) {
    return getID(getType(type), num);
  }

  public final static int getID(String name) {
    int dot = name.indexOf('.');
    if (dot == -1) throw new IllegalArgumentException(name);
    String type = name.substring(0, dot);
    int num = Integer.parseInt(name.substring(dot+1));
    return getID(type, num);
  }

  public final static int getType(String name) {
    name = name.toLowerCase();
    try {
      int type = 0;
      while (!name.equals(typenames[type])) type++;
      return type;
    } catch (ArrayIndexOutOfBoundsException e) {
      throw new IllegalArgumentException(name);
    }
  }

  public final static int getType(int id) {
    return id >> 0xb;
  }

  public final static int getNum(int id) {
    return id & 0x7ff;
  }

  public final static String getName(int restype, int resnum) {
    String n = Integer.toString(resnum);
    while (n.length() < 3) n = "0" + n;
    return typenames[restype] + "." + n;
  }

  public final String getName() {
    return getName(restype, resnum);
  }

  public final String toString() {
    return getName();
  }

  Component makeViewer() {
    return new GenericViewer(b);
  }

  public void view() {
    Component c = makeViewer();
    Frame f = new BafFrame(getName(), c);
    f.show();
  }
}

