// ---------------------------------------------------------------------------
// - Message.cpp                                                             -
// - standard object library - message 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-2013 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Item.hpp"
#include "Stdsid.hxx"
#include "Vector.hpp"
#include "Utility.hpp"
#include "Integer.hpp"
#include "Message.hpp"
#include "Runnable.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "InputStream.hpp"
#include "OutputStream.hpp"

namespace afnix {
  
  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------
  
  // the info message code
  static const char MESG_INFO_CODE = (char) 0x01;
  // the warning message code
  static const char MESG_WARN_CODE = (char) 0x02;
  // the error message code
  static const char MESG_MERR_CODE = (char) 0x03;
  // the fatal message code
  static const char MESG_FAIL_CODE = (char) 0x04;

  // convert a message type to a character code
  static char to_char (const Message::t_emsg type) {
    char result = nilc;
    switch (type) {
    case Message::INFO:
      result = MESG_INFO_CODE;
      break;
    case Message::WARNING:
      result = MESG_WARN_CODE;
      break;
    case Message::ERROR:
      result = MESG_MERR_CODE;
      break;
    case Message::FATAL:
      result = MESG_FAIL_CODE;
      break;
    } 
    return result;
  }

  // convert a character code to a message type
  static Message::t_emsg to_emsg (const char c) {
    // convert the character code
    if (c == MESG_INFO_CODE) return Message::INFO;
    if (c == MESG_WARN_CODE) return Message::WARNING;
    if (c == MESG_MERR_CODE) return Message::ERROR;
    if (c == MESG_FAIL_CODE) return Message::FATAL;
    // invalid message type code
    throw Exception ("message-error", "invalid serial message type code");
  }
 
  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default message

  Message::Message (void) {
    d_type = INFO;
    d_code = 0;
  }

  // create a message by name

  Message::Message (const String& name) {
    d_type = INFO;
    d_name = name;
    d_code = 0;
  }

  // create a message by name and info

  Message::Message (const String& name, const String& info) {
    d_type = INFO;
    d_name = name;
    d_info = info;
    d_code = 0;
  }

  // create a message by name, info and code

  Message::Message (const String& name, const String& info, const long code) {
    d_type = INFO;
    d_name = name;
    d_info = info;
    d_code = code;
  }

  // create a message by type, name, info and code

  Message::Message (const t_emsg type, const String& name, const String& info,
		    const long code) {
    d_type = type;
    d_name = name;
    d_info = info;
    d_code = code;
  }

  // copy construct this message

  Message::Message (const Message& that) {
    that.rdlock ();
    try {
      d_type = that.d_type;
      d_name = that.d_name;
      d_info = that.d_info;
      d_code = that.d_code;
      that.unlock ();
    } catch (...) {
      that.unlock ();
      throw;
    }
  }

  // return the class name

  String Message::repr (void) const {
    return "Message";
  }
 
  // return a clone of this object

  Object* Message::clone (void) const {
    return new Message (*this);
  }

  // return the message serial code

  t_byte Message::serialid (void) const {
    return SERIAL_MESG_ID;
  }

  // serialize this message

  void Message::wrstream (OutputStream& os) const {
    rdlock ();
    try {
      // save the message type
      os.write (to_char (d_type));
      // save the name and info
      d_name.wrstream (os);
      d_info.wrstream (os);
      // save the message code
      Integer code (d_code);
      code.wrstream (os);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // deserialize this message

  void Message::rdstream (InputStream& is) {
    wrlock ();
    try {
      // read the message type
      d_type = to_emsg (is.read ());
      // read the name and info
      d_name.rdstream (is);
      d_info.rdstream (is);
      // read the message code
      Integer code;
      code.rdstream (is);
      d_code = code.tolong ();
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // assign a message to this one

  Message& Message::operator = (const Message& that) {
    // check for self-assignation
    if (this == &that) return *this;
    // lock and assign
    wrlock ();
    that.rdlock ();
    try {
      // assign locally
      d_type = that.d_type;
      d_name = that.d_name;
      d_info = that.d_info;
      d_code = that.d_code;
      // unlock and return
      unlock ();
      that.unlock ();
      return *this;
    } catch (...) {
      unlock ();
      that.unlock ();
      throw;
    }
  }

  void Message::set (const t_emsg type, const String& name, const String& info,
		     const long   code) {
    wrlock ();
    try {
      d_type = type;
      d_name = name;
      d_info = info;
      d_code = code;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the message type

  void Message::settype (const t_emsg type) {
    wrlock ();
    try {
      d_type = type;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the message type

  Message::t_emsg Message::gettype (void) const {
    rdlock ();
    try {
      t_emsg result = d_type;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the message name

  void Message::setname (const String& name) {
    wrlock ();
    try {
      d_name = name;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the message name

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

  // set the message info

  void Message::setinfo (const String& info) {
    wrlock ();
    try {
      d_info = info;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the message info

  String Message::getinfo (void) const {
    rdlock ();
    try {
      String result = d_info;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the message code

  void Message::setcode (const long code) {
    wrlock ();
    try {
      d_code = code;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the message code

  long Message::getcode (void) const {
    rdlock ();
    try {
      long result = d_code;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // format the message as a string

  String Message::format (void) const {
    rdlock ();
    try {
      String result;
      switch (d_type) {
      case INFO:
	result = "[I:";
	break;
      case WARNING:
	result = "[W:";
	break;
      case ERROR:
	result = "[E:";
	break;
      case FATAL:
	result = "[F:";
	break;
      }
      // add the message code
      result += Utility::tostring (d_code) + ']';
      // add the message name
      if (d_name.isnil () == false) {
	result += ' ' ;
	result += d_name;
      }
      // add the message info
      if (d_info.isnil () == false) {
	result += " (" ;
	result += d_info;
	result += ')';
      }
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

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

  // the object eval quarks
  static const long QUARK_INFO = String::intern ("INFO");
  static const long QUARK_WARN = String::intern ("WARNING");
  static const long QUARK_MERR = String::intern ("ERROR");
  static const long QUARK_FAIL = String::intern ("FATAL");
  static const long QUARK_MESG = String::intern ("Message");

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

  // the object supported quarks
  static const long QUARK_SET     = zone.intern ("set");
  static const long QUARK_FORMAT  = zone.intern ("format");
  static const long QUARK_SETTYPE = zone.intern ("set-type");
  static const long QUARK_GETTYPE = zone.intern ("get-type");
  static const long QUARK_SETNAME = zone.intern ("set-name");
  static const long QUARK_GETNAME = zone.intern ("get-name");
  static const long QUARK_SETINFO = zone.intern ("set-info");
  static const long QUARK_GETINFO = zone.intern ("get-info");
  static const long QUARK_SETCODE = zone.intern ("set-code");
  static const long QUARK_GETCODE = zone.intern ("get-code");

  // map an item to a message type
  static inline Message::t_emsg item_to_emsg (const Item& item) {
    // check for a stream item 
    if (item.gettid () != QUARK_MESG) {
      throw Exception ("item-error", "item is not a message item");
    }
    // map the item to the enumeration
    long quark = item.getquark (); 
    if (quark == QUARK_INFO) return Message::INFO;
    if (quark == QUARK_WARN) return Message::WARNING;
    if (quark == QUARK_MERR) return Message::ERROR;
    if (quark == QUARK_FAIL) return Message::FATAL;
    throw Exception ("item-error", "cannot map item to message type");
  }

  // map a type to an item
  static inline Item* emsg_to_item (const Message::t_emsg type) {
    Item* result  = nilp;
    switch (type) {
    case Message::INFO:
      result = new Item (QUARK_MESG, QUARK_INFO);
      break;
    case Message::WARNING:
      result = new Item (QUARK_MESG, QUARK_WARN);
      break;
    case Message::ERROR:
      result = new Item (QUARK_MESG, QUARK_MERR);
      break;
    case Message::FATAL:
      result = new Item (QUARK_MESG, QUARK_FAIL);
      break;
    }
    return result;
  }

  // create a new object in a generic way
  
  Object* Message::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();

    // check 0 argument
    if (argc == 0) return new Message;
    // check 1 argument
    if (argc == 1) {
      String name = argv->getstring (0);
      return new Message (name);
    }
    // check for 2 arguments
    if (argc == 2) {
      String name = argv->getstring (0);
      String info = argv->getstring (1);
      return new Message (name, info);
    }
    // check for 3 arguments
    if (argc == 3) {
      String name = argv->getstring (0);
      String info = argv->getstring (1);
      long   code = argv->getlong   (2);
      return new Message (name, info, code);
    }
    // check for 4 arguments
    if (argc == 4) {
      Object* obj = argv->get (0);
      Item*  iobj = dynamic_cast <Item*> (obj);
      if (iobj == nilp) {
	throw Exception ("type-error", "invalid object for message type",
			 Object::repr (obj));
      }
      String name = argv->getstring (1);
      String info = argv->getstring (2);
      long   code = argv->getlong   (3);
      return new Message (item_to_emsg (*iobj), name, info, code);
    }
    throw Exception ("argument-error", "too many argument for message");
  }

  // evaluate a quark statically

  Object* Message::meval (Runnable* robj, Nameset* nset, const long quark) {
    if (quark == QUARK_INFO)
      return new Item (QUARK_MESG, QUARK_INFO);
    if (quark == QUARK_WARN) 
      return new Item (QUARK_MESG, QUARK_WARN);
    if (quark == QUARK_MERR) 
      return new Item (QUARK_MESG, QUARK_MERR);
    if (quark == QUARK_FAIL) 
      return new Item (QUARK_MESG, QUARK_FAIL);
    throw Exception ("eval-error", "cannot evaluate member",
                     String::qmap (quark));
  }

  // return true if the given quark is defined

  bool Message::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Serial::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }

  // apply this obejct with a set of arguments and a quark

  Object* Message::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_FORMAT)  return new String   (format  ());
      if (quark == QUARK_GETTYPE) return emsg_to_item (gettype ());
      if (quark == QUARK_GETNAME) return new String   (getname ());
      if (quark == QUARK_GETINFO) return new String   (getinfo ());
      if (quark == QUARK_GETCODE) return new Integer  (getcode ());
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_SETTYPE) {
	Object* obj = argv->get (0);
	Item*  iobj = dynamic_cast <Item*> (obj);
	if (iobj == nilp) {
	  throw Exception ("type-error", "invalid object for message type",
			   Object::repr (obj));
	}
	settype (item_to_emsg (*iobj));
	return nilp;
      }
      if (quark == QUARK_SETNAME) {
	String name = argv->getstring (0);
	setname (name);
	return nilp;
      }
      if (quark == QUARK_SETINFO) {
	String info = argv->getstring (0);
	setinfo (info);
	return nilp;
      }
      if (quark == QUARK_SETCODE) {
	long code = argv->getlong (0);
	setcode (code);
	return nilp;
      }
    }
    // dispatch 4 arguments
    if (argc == 4) {
      if (quark == QUARK_SET) {
	Object* obj = argv->get (0);
	Item*  iobj = dynamic_cast <Item*> (obj);
	if (iobj == nilp) {
	  throw Exception ("type-error", "invalid object for message type",
			   Object::repr (obj));
	}
	String name = argv->getstring (1);
	String info = argv->getstring (2);
	long   code = argv->getlong   (3);
	set (item_to_emsg (*iobj), name, info, code);
	return nilp;
      }
    }
    // call the serial method
    return Serial::apply (robj, nset, quark, argv);
  }
}
