// ---------------------------------------------------------------------------
// - Module.cpp                                                              -
// - afnix engine - module 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-2023 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Vector.hpp"
#include "Module.hpp"
#include "Reader.hpp"
#include "Boolean.hpp"
#include "InputFile.hpp"
#include "Extracter.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "InputMapped.hpp"
#include "OutputBuffer.hpp"

namespace afnix {

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

  // the afnix module magic number
  const long CV_MOD_SIZE   = 4L;
  const char CV_MOD_MGIC[] = {'\177', 'A', 'X', 'C'};

  // this function check that the header matches the axc magic number
  static Module::t_mfmt get_module_format (InputStream* is) {
    // check for nil and reset
    if (is == nullptr) return Module::MFMT_NONE;
    // read in the magic number
    char mbuf[CV_MOD_SIZE];
    for (long k = 0L; k < CV_MOD_SIZE; k++) {
      mbuf[k] = is->read ();
      if (mbuf[k] != CV_MOD_MGIC[k]) {
	is->pushback (mbuf, k+1);
	return Module::MFMT_TEXT;
      }
    }
    return Module::MFMT_CBIN;
  }

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

  // create a null module

  Module::Module (void) {
    d_mfmt = MFMT_NONE;
    p_frmr = nullptr;
  }

  // create a new module by name

  Module::Module (const String& name) {
    d_mfmt = MFMT_NONE;
    p_frmr = nullptr;
    // create an input stream
    InputStream* is = new InputFile (name); Object::iref (is);
    // bind the input stream
    if (bind (is, name) == false) {
      Object::dref (is);
      throw Exception ("module-error", "cannot bind module", name);
    }
    // clean the stream
    Object::tref (is);
  }

  // create a new module by buffer

  Module::Module (const Buffer& ibuf) {
    d_mfmt = MFMT_NONE;
    p_frmr = nullptr;
    // create an input stream
    InputMapped* is = new InputMapped (ibuf); Object::iref (is);
    // bind the input stream
    if (bind (is) == false) {
      Object::dref (is);
      throw Exception ("module-error", "cannot bind module by buffer");
    }
    // clean the stream
    Object::tref (is);
  }

  // create a module by stream and name

  Module::Module (InputStream* is, const String& name) {
    d_mfmt = MFMT_NONE;
    p_frmr = nullptr;    
    // bind the input stream
    if (bind (is, name) == false) {
      throw Exception ("module-error", "cannot bind module", name);
    }
  }

  // create a new module by buffer and name

  Module::Module (const Buffer& ibuf, const String& name) {
    d_mfmt = MFMT_NONE;
    p_frmr = nullptr;
    // create an input stream
    InputMapped* is = new InputMapped (ibuf); Object::iref (is);
    // bind the input stream
    if (bind (is, name) == false) {
      Object::dref (is);
      throw Exception ("module-error", "cannot bind module by buffer");
    }
    // clean the stream
    Object::tref (is);
  }


  // delete this module

  Module::~Module (void) {
    Object::dref (p_frmr);
  }

  // return the class name

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

  // bind a module by input stream

  bool Module::bind (InputStream* is) {
    wrlock ();
    try {
      // check for bound module
      if ((d_mfmt != MFMT_NONE) || (p_frmr != nullptr) || (is == nullptr)) {
	unlock ();
	return false;
      }
      // find out the module type
      d_mfmt = get_module_format (is);
      // create a new form reader
      if (d_mfmt == MFMT_TEXT) {
	Object::iref (p_frmr = new Reader (is));
      }
      if (d_mfmt == MFMT_CBIN) {
	// force the natural encoding in compiled mode
	if (is != nullptr) is->setemod (Encoding::getnem ());
	// create the form extractor
	Object::iref (p_frmr = new Extracter (is));
      }
      bool status = (d_mfmt == MFMT_NONE) ? false : true;
      unlock ();
      return status;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // bind a module by input stream and name

  bool Module::bind (InputStream* is, const String& name) {
    wrlock ();
    try {
      // bind the module by stream
      bool status = bind (is);
      // bind the module name
      if (status == true) {
	auto frmr = dynamic_cast<Reader*>(p_frmr);
	if (frmr != nullptr) frmr->setname (name);
	d_name = name;
      }
      unlock ();
      return status;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get the next form available in this module

  Form* Module::parse (void) {
    rdlock ();
    try {
      // check for a bound module
      if ((d_mfmt == MFMT_NONE) || (p_frmr == nullptr)) {
	unlock ();
	return nullptr;
      }
      // collect the next form
      Form* result = p_frmr->parse ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return true if the module is a text module

  bool Module::istext (void) const {
    rdlock ();
    try {
      bool status = (d_mfmt == MFMT_TEXT);
      unlock ();
      return status;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the module format

  Module::t_mfmt Module::getmfmt (void) const {
    rdlock ();
    try {
      t_mfmt result = d_mfmt;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the module name

  String Module::getname (void) const {
    rdlock ();
    try {
      String result = d_name;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the reader line number

  long Module::getlnum (void) const {
    rdlock ();
    try {
      // check that we have a form reader
      if (p_frmr == nullptr) {
	throw Exception ("module-error", "no former installed");
      }
      // get the line number
      long result = p_frmr->getlnum ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // write a module to an output stream

  bool Module::write (OutputStream& os) {
    rdlock ();
    try {
      // check for bound module
      if (d_mfmt == MFMT_NONE) {
	unlock ();
	return false;
      }
      // write the module header
      if (os.write (CV_MOD_MGIC, CV_MOD_SIZE) != CV_MOD_SIZE) {
	throw Exception ("module-error", "cannot write module", d_name);
      }
      // parse and serialize
      while (true) {
	Cons* cons = parse ();
	if (cons == nullptr) break;
	cons->serialize (os);
	Object::dref (cons);
      }
      unlock ();
      return true;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get e module buffer content

  Buffer Module::tobuffer (void) {
    wrlock ();
    try {
      OutputBuffer os;
      if (write (os) == false) {
	throw Exception ("module-error", "cannot write module as buffer");
      }
      Buffer result = os.tobuffer ();
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

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

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

  // the object supported quarks
  static const long QUARK_BIND  = zone.intern ("bind");
  static const long QUARK_WRITE = zone.intern ("write");
  static const long QUARK_TEXTP = zone.intern ("text-p");
  static const long QUARK_TOBUF = zone.intern ("to-buffer");

  // create a new object in a generic way

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

    // check for 0 argument
    if (argc == 0L) return new Module;

    // check for 1 argument
    if (argc == 1) {
      Object* obj = argv->get (0);
      // check for a string
      auto* sobj = dynamic_cast <String*> (obj);
      if (sobj != nullptr) return new Module (*sobj);
      // check for a buffer
      auto* bobj = dynamic_cast <Buffer*> (obj);
      if (bobj != nullptr) return new Module (*bobj);
      // invalid object
      throw Exception ("type-error", "invalid object module",
		       Object::repr (obj));
    }
    // check for 2 arguments
    if (argc == 2) {
      Object* obj = argv->get (0);
      String name = argv->getstring (1);
      // check for an input stream
      auto* is = dynamic_cast <InputStream*> (obj);
      if (is != nullptr) return new Module (is, name);
      // check for a buffer
      auto* bobj = dynamic_cast <Buffer*> (obj);
      if (bobj != nullptr) return new Module (*bobj, name);
      // invalid object
      throw Exception ("type-error", "invalid object with moduel",
		       Object::repr (obj));
    }
    throw Exception ("argument-error", "too many arguments with module ");
  }

  // return true if the given quark is defined

  bool Module::isquark (const long quark, const bool hflg) const {
    rdlock ();
    try {
      if (zone.exists (quark) == true) {
	unlock ();
	return true;
      }      
      bool result = hflg ? Nameable::isquark (quark, hflg) : false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // apply this object with a set of arguments and a quark
  
  Object* Module::apply (Evaluable* zobj, Nameset* nset, const long quark,
			 Vector* argv) {
    
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();
    
    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_TEXTP) return new Boolean (istext());
      if (quark == QUARK_TOBUF) return new Buffer (tobuffer());
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_BIND) {
	Object* obj = argv->get (0);
	// check for an input stream
	auto is = dynamic_cast <InputStream*> (obj);
	if (is != nullptr) return new Boolean (bind (is));
	// invalid object
	throw Exception ("type-error", "invalid object with module bind",
			 Object::repr (obj));
      }
      if (quark == QUARK_WRITE) {
	Object* obj = argv->get (0);
	// check for an output stream
	auto os = dynamic_cast <OutputStream*> (obj);
	if (os != nullptr) return new Boolean (write (*os));
	// invalid object
	throw Exception ("type-error", "invalid object with module write",
			 Object::repr (obj));
      }
    }
    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_BIND) {
	Object* obj = argv->get (0);
	String name = argv->getstring (1);
	// check for an input stream
	auto* is = dynamic_cast <InputStream*> (obj);
	if (is != nullptr) return new Boolean (bind (is, name));
	// invalid object
	throw Exception ("type-error", "invalid object with module bind",
			 Object::repr (obj));
      }
    }
    // fallback with the nameable method
    return Nameable::apply (zobj, nset, quark, argv);
  }
}
