// ---------------------------------------------------------------------------
// - Datum.cpp                                                               -
// - afnix:tcz service - datum 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 "Avi.hpp"
#include "Datum.hpp"
#include "Tczdb.hpp"
#include "Tczsid.hxx"
#include "Vector.hpp"
#include "Number.hpp"
#include "Boolean.hpp"
#include "Evaluable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "AliasTable.hpp"

namespace afnix {

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

  // datum alias table
  static const long   AT_DTM_SIZE = 8L;
  static const String AT_DTM_DATA[AT_DTM_SIZE] =
    {
      PN_PRT_NAME, PN_DTM_NAME,
      PN_PRT_INFO, PN_DTM_INFO,
      PN_PRT_UUID, PN_DTM_UUID,
      PN_PRT_PLST, PN_DTM_PLST
    };
  
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default datum

  Datum::Datum (void) {
    d_cmod = Tcz::CMOD_NONE;
    p_rval = nullptr;
  }
  
  // create a datum by name

  Datum::Datum (const String& name) : Part (name) {
    d_cmod = Tcz::CMOD_NONE;
    p_rval = nullptr;
  }

  // create a datum by name and info

  Datum::Datum (const String& name, const String& info) : Part (name,info) {
    d_cmod = Tcz::CMOD_NONE;
    p_rval = nullptr;
  }
  
  // copy construct this datum

  Datum::Datum (const Datum& that) {
    that.rdlock ();
    try {
      // assign the base part
      Part::operator = (that);
      // copy locally
      d_cmod = that.d_cmod;
      Object::iref (p_rval = that.p_rval);
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }
  
  // copy move this datum

  Datum::Datum (Datum&& that) noexcept {
    that.wrlock ();
    try {
      // move base part
      Part::operator = (static_cast<Part&&>(that));
      // copy locally
      d_cmod = that.d_cmod; that.d_cmod = Tcz::CMOD_NONE;
      p_rval = that.p_rval; that.p_rval = nullptr;
    } catch (...) {
      d_cmod = Tcz::CMOD_NONE;
      p_rval = nullptr;
    }
    that.unlock ();
  }
  
  // destroy this datum

  Datum::~Datum (void) {
    Object::dref (p_rval);
  }
  
  // assign a datum to this one

  Datum& Datum::operator = (const Datum& that) {
    // check for self assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.rdlock ();
    try {
      // assign base object
      Part::operator = (that);
      // assign locally
      d_cmod = that.d_cmod;
      Object::iref (that.p_rval); Object::dref (p_rval); p_rval = that.p_rval;
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }
  
  // move a datum to this one

  Datum& Datum::operator = (Datum&& that) noexcept {
    // check for self-assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.wrlock ();
    try {
      // assign base object
      Part::operator = (static_cast<Part&&>(that));
      // move locally
      d_cmod = that.d_cmod; that.d_cmod = Tcz::CMOD_NONE;
      p_rval = that.p_rval; that.p_rval = nullptr;
    } catch (...) {
      d_cmod = Tcz::CMOD_NONE;
      p_rval = nullptr;
    }
    unlock ();
    that.unlock ();
    return *this;
  }
  
  // return the datum class name
  
  String Datum::repr (void) const {
    return "Datum";
  }
  
  // return a clone of this object
  
  Object* Datum::clone (void) const {
    return new Datum (*this);
  }
  
  // return the serial did

  t_word Datum::getdid (void) const {
    return SRL_DEOD_TCZ;
  }

  // return the serial sid
  
  t_word Datum::getsid (void) const {
    return SRL_DTUM_SID;
  }

  // serialize this datum

  void Datum::wrstream (OutputStream& os) const {
    rdlock ();
    try {
      // serialize base object
      Part::wrstream (os);
      // serialize locally
      Serial::wrbyte (d_cmod, os);
      if (p_rval == nullptr) {
	Serial::wrnilid (os);
      } else {
	auto sobj = dynamic_cast <Serial*> (p_rval);
	if (sobj == nullptr) {
	  throw Exception ("datum-error", "cannot serialize object", 
			   p_rval->repr ());
	}
	sobj->serialize (os);
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // deserialize this datum

  void Datum::rdstream (InputStream& is) {
    wrlock ();
    try {
      // deserialize base object
      Part::rdstream (is);
      // deserialize locally
      d_cmod = static_cast<Tcz::t_cmod>(Serial::rdbyte (is));
      Object::iref (p_rval = Serial::deserialize (is));
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the datum plist

  Plist Datum::getplst (void) const {
    // the alias table
    static const AliasTable atbl (AT_DTM_SIZE, AT_DTM_DATA);
    rdlock ();
    try {
      // get the base plist
      Plist result = atbl.map (Part::getplst ());
      // add the resource length
      result.add (PN_DTM_CMOD, PI_DTM_CMOD, Tcz::tostring(d_cmod));
      result.add (PN_DTM_TYPE, PI_DTM_TYPE, Object::repr (p_rval));
      // check for selected values
      auto lval = dynamic_cast<Literal*> (p_rval);
      if (lval != nullptr) {
	result.add (PN_DTM_DVAL, PI_DTM_DVAL, lval->toliteral ());
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a blob object view

  HashTable Datum::toview (void) const {
    // the alias table
    static const AliasTable atbl (AT_DTM_SIZE, AT_DTM_DATA);
    rdlock ();
    try {
      // get part view
      HashTable result = atbl.map (Part::toview ());
      // add datum specific view
      result.add (PN_DTM_CMOD, new String (Tcz::tostring(d_cmod)));
      result.add (PN_DTM_TYPE, new String (Object::repr (p_rval)));
      // check for literal values
      auto lval = dynamic_cast<Literal*> (p_rval);
      if (lval != nullptr) result.add (PN_DTM_DVAL, lval);
      // check for number
      auto nval = dynamic_cast<Number*> (p_rval);
      if (nval != nullptr) {
	result.add (PN_DTM_FRMT, new String(nval->tofrmt ()));
      }
      // check for vector
      auto vval = dynamic_cast<Avi*>(p_rval);
      if (vval != nullptr) {
	result.add (PN_DTM_FRMT, new String (vval->tofrmt()));
	result.add (PN_DTM_DVAL, new Vector (vval->tovector()));
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // bind the datum

  bool Datum::bind (const Tcz::t_cmod cmod, Object* rval) {
    wrlock ();
    try {
      d_cmod = cmod;
      Object::iref (rval); Object::dref (p_rval); p_rval = rval;
      unlock ();
      return true;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get the datum content mode

  Tcz::t_cmod Datum::getcmod (void) const {
    rdlock ();
    try {
      Tcz::t_cmod result = d_cmod;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // get the datum object

  Object* Datum::getdval (void) const {
    rdlock ();
    try {
      Object* result = p_rval;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // -------------------------------------------------------------------------
  // - 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_BIND    = zone.intern ("bind");
  static const long QUARK_GETDVAL = zone.intern ("get-value");
  static const long QUARK_GETCMOD = zone.intern ("get-content-mode");

  // create a new object in a generic way

  Object* Datum::mknew (Vector* argv) {
    long argc = (argv == nullptr) ? 0 : argv->length ();
    // create a default datum
    if (argc == 0) return new Datum;
    // check for 1 argument
    if (argc == 1) {
      String name = argv->getstring (0);
      return new Datum (name);
    }
    // check for 2 arguments
    if (argc == 2) {
      String name = argv->getstring (0);
      String info = argv->getstring (1);
      return new Datum (name, info);
    }
    throw Exception ("argument-error",
                     "too many argument with datum constructor");
  }

  // return true if the given quark is defined

  bool Datum::isquark (const long quark, const bool hflg) const {
    rdlock ();
    try {
      if (zone.exists (quark) == true) {
	unlock ();
	return true;
      }
      bool result = hflg ? Part::isquark (quark, hflg) : false;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* Datum::apply (Evaluable* zobj, Nameset* nset,
			       const long quark, Vector* argv) {
    // get the number of arguments
    long argc = (argv == nullptr) ? 0 : argv->length ();

    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_GETCMOD) return Tcz::toitem (getcmod ());
      if (quark == QUARK_GETDVAL) {
	rdlock ();
	try {
	  Object* result = getdval ();
	  zobj->post (result);
	  unlock ();
	  return result;
	} catch (...) {
	  unlock ();
	  throw;
	}
      }
    }
    // check for 2 arguments
    if (argc == 2) {
      if (quark == QUARK_BIND) {
	Object* obj = argv->get (0);
	Item* item = dynamic_cast <Item*> (obj);
        if (item == nullptr) {
	  throw Exception ("argument-error", "invalid object as datum mode",
			   Object::repr (obj));
	}
	Tcz::t_cmod cmod = Tcz::tocmod (*item);
	obj = argv->get (1);  
	return new Boolean (bind (cmod, obj));
      }
    }
    // call the part method
    return Part::apply (zobj, nset, quark, argv);
  }
}
