package org.clearsilver;

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

public class CS {
  public int csptr;
  
  protected HDF globalHDF;

  static { 
    try {
      System.loadLibrary("clearsilver-jni");
    } catch ( UnsatisfiedLinkError e ) {
      System.out.println("Could not load library 'clearsilver-jni'");
      System.exit(1);
    }
  }
  
  public CS(HDF ho) {
    this.globalHDF = null;
    csptr = _init(ho.hdfptr);
  }

  // Construct with global HDF to search if local HDF returns null
  public CS(HDF ho, HDF global) {
    this(ho);

    this.globalHDF = global;
    if (global != null) {
      _setGlobalHdf(csptr,global.hdfptr);
    }
  }

  // Specify a new/different global HDF
  public void setGlobalHDF(HDF global) {
    _setGlobalHdf(csptr,global.hdfptr);
    this.globalHDF = global;
  }

  // Return global hdf in use
  public HDF getGlobalHDF() {
    return this.globalHDF;
  }

  public void close() {
    if (csptr != 0) {
      _dealloc(csptr);
      csptr = 0;
    }
  }    

  public void finalize() {
    close();
  }

  public void parseFile(String filename) {
    if (csptr == 0) {
      throw new NullPointerException("CS is closed.");
    }
    _parseFile(csptr,filename);
  }

  public void parseStr(String content) {
    if (csptr == 0) {
      throw new NullPointerException("CS is closed.");
    }
    _parseStr(csptr,content);
  }

  public String render() {
    if (csptr == 0) {
      throw new NullPointerException("CS is closed.");
    }
    return _render(csptr);
  }
  
  private native int    _init(int ptr);
  private native void   _dealloc(int ptr);
  private native void   _parseFile(int ptr,String filename);
  private native void   _parseStr(int ptr, String content);
  private native String _render(int ptr);
  private native void   _setGlobalHdf(int csptr, int hdfptr);
};
