// ---------------------------------------------------------------------------
// - InputMapped.cpp                                                         -
// - standard object library - input mapped file class implementation        -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - This program  is  distributed in  the hope  that it will be useful, but -
// - without  any  warranty;  without  even   the   implied    warranty   of -
// - merchantability or fitness for a particular purpose.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2006 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Vector.hpp"
#include "Integer.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "InputMapped.hpp"
#include "cmem.hpp"
#include "csio.hpp"

namespace afnix {

  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------

  // this function open a file by name and return a file id
  static int open_file (const String& name) {
    // check if the file exist
    char* fname = name.tochar ();
    // try to open the file
    int sid = c_openr (fname);
    if (sid < 0) {
      delete [] fname;
      return -1;
    }
    delete [] fname;
    return sid;
  }

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a new mapped file by name

  InputMapped::InputMapped (const String& name) {
    d_buffer.reset ();
    // try to open the file
    int sid = open_file (name);
    if (sid == -1) throw Exception ("open-error", "cannot open file", name);
    // get the file size
    t_long size = c_fsize (sid);
    // try to map it
    p_mbuf = (char*) c_mmap (sid, size, 0);
    if (p_mbuf == nilp) 
      throw Exception ("map-error", "cannot map file", name);
    // save map data
    d_name = name;
    d_size = size;
    d_foff = 0;
    d_mark = 0;
    // close the file
    c_close (sid);
  }

  // create a new mapped file by name, size and offset

  InputMapped::InputMapped (const String& name, const t_long size, 
			    const t_long foff) {
    d_buffer.reset ();
    // try to open the file
    int sid = open_file (name);
    if (sid == -1) throw Exception ("open-error", "cannot open file", name);
    // try to map it
    p_mbuf = (char*) c_mmap (sid, size, foff);
    if (p_mbuf == nilp) 
      throw Exception ("map-error", "cannot map file", name);
    // save map data
    d_name = name;
    d_size = size;
    d_foff = foff;
    d_mark = 0;
    // close the file
    c_close (sid);
  }

  // destroy this mapped file

  InputMapped::~InputMapped (void) {
    c_munmap (p_mbuf, d_size);
  }

  // return the class name

  String InputMapped::repr (void) const {
    return "InputMapped";
  }

  // read one character from the input stream.

  char InputMapped::read (void) {
    wrlock ();
    try {
      // check the pushback buffer first
      if (d_buffer.empty () == false) {
	long result = d_buffer.read ();
	unlock ();
	return result;
      }
      // check for eof
      if (d_mark == d_size) {
	unlock ();
	return eofc;
      }
      // get next character
      char result = p_mbuf[d_mark++];
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the eof flag is set

  bool InputMapped::iseof (void) const {
    wrlock ();
    try {
      bool result = !valid (0);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if we can read a character

  bool InputMapped::valid (const long tout) const {
    wrlock ();
    try {
      if (d_buffer.empty () == false) {
	unlock ();
	return true;
      }
      bool result = (d_mark == d_size) ? false : true;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the input stream at a certain position

  void InputMapped::lseek (const t_long pos) {
    wrlock ();
    // check position
    if ((pos >= 0) && (pos < d_mark)) {
      d_mark = pos;
    } else {
      if (pos < 0)       d_mark = 0;
      if (pos >= d_size) d_mark = d_size;
    }
    // reset everything
    d_buffer.reset ();
    unlock ();
  }

  // return the mapped file name

  String InputMapped::getname (void) const {
    rdlock ();
    String result = d_name;
    unlock ();
    return result;
  }

  // return the mapped file size

  t_long InputMapped::length (void) const {
    rdlock ();
    t_long result = d_size;
    unlock ();
    return result;
  }

  // return the mapped file offset

  t_long InputMapped::foffset (void) const {
    rdlock ();
    t_long result = d_foff;
    unlock ();
    return result;
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 3;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_LSEEK     = zone.intern ("lseek");
  static const long QUARK_LENGTH    = zone.intern ("length");
  static const long QUARK_GETOFFSET = zone.intern ("get-offset");

  // create a new object in a generic way

  Object* InputMapped::mknew (Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();

    // check for 1 argument
    if (argc == 1) {
      String name = argv->getstring (0);
      return new InputMapped (name);
    }
    // check for 3 arguments
    if (argc == 3) {
      String name = argv->getstring (0);
      t_long size = argv->getint (0);
      t_long foff = argv->getint (1);
      return new InputMapped (name, size, foff);
    }
    throw Exception ("argument-error", "too many arguments with mapped file");
  }

  // return true if the given quark is defined

  bool InputMapped::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }      
    // check the nameable class
    bool result = hflg ? Nameable::isquark (quark, hflg) : false;
    // check the input class
    if (result == false) {
      result = hflg ? Input::isquark (quark, hflg) : false;
    }
    unlock ();
    return result;
  }

  // apply this object with a set of arguments and a quark
  
  Object* InputMapped::apply (Runnable* robj, Nameset* nset, const long quark,
			      Vector* argv) {
    
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_LENGTH)    return new Integer (length  ());
      if (quark == QUARK_GETOFFSET) return new Integer (foffset ());
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_LSEEK) {
	t_long pos = argv->getint (0);
	lseek (pos);
	return nilp;
      }
    }
    // check the nameable class
    if (Nameable::isquark (quark, true) == true) {
      return Nameable::apply (robj, nset, quark, argv);
    }
    // fallbak with the input method
    return Input::apply (robj, nset, quark, argv);
  }
}
