// ---------------------------------------------------------------------------
// - Logger.cpp                                                              -
// - standard object library - message logger 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-2008 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Item.hpp"
#include "Date.hpp"
#include "Vector.hpp"
#include "Logger.hpp"
#include "Utility.hpp"
#include "Integer.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"
#include "OutputFile.hpp"

namespace afnix {

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

  // the defqult stream operation mode
  static const String LOG_MODE_DEF = "UTF-8";

  // the message log structure
  struct s_mlog {
    // the log level
    long   d_mlvl;
    // the message time
    t_long d_time;
    // the message value
    String d_mesg;
    // create a default message log
    s_mlog (void) {
      reset ();
    }
    // assign a message log to this one
    s_mlog& operator = (const s_mlog& that) {
      if (this == &that) return *this;
      d_mlvl = that.d_mlvl;
      d_time = that.d_time;
      d_mesg = that.d_mesg;
      return *this;
    }
    // reset the message log
    void reset (void) {
      d_mlvl = 0;
      d_time = 0;
      d_mesg = "";
    }
    // set a message with a log level
    void set (const String& mesg, const long mlvl) {
      d_mlvl = mlvl;
      d_time = Time::gettclk ();
      d_mesg = mesg;
    }
  };

  // logger initial size
  static const long LOGGER_SIZE = 256;

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------
  
  // create a new logger
  
  Logger::Logger (void) {
    p_os   = nilp;
    d_size = LOGGER_SIZE;
    p_mlog = new s_mlog[d_size];
    reset ();
  }
  
  // create a new logger by size
  
  Logger::Logger (const long size) {
    p_os   = nilp;
    d_size = (size > 0) ? size : LOGGER_SIZE;
    p_mlog = new s_mlog[d_size];
    reset ();
  }

  // create a new logger by info
  
  Logger::Logger (const String& info) {
    p_os   = nilp;
    d_size = LOGGER_SIZE;
    p_mlog = new s_mlog[d_size];
    d_info = info;
    reset ();
  }

  // create a new logger by size and info
  
  Logger::Logger (const long size, const String& info) {
    p_os   = nilp;
    d_size = (size > 0) ? size : LOGGER_SIZE;
    p_mlog = new s_mlog[d_size];
    d_info = info;
    reset ();
  }
  
  // destroy this logger

  Logger::~Logger (void) {
    Object::dref (p_os);
    delete [] p_mlog;
  }

  // return the class name

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

  // reset this logger class

  void Logger::reset (void) {
    wrlock ();
    for (long i = 0; i < d_size; i++) p_mlog[i].reset ();
    d_mcnt = 0;
    d_mpos = 0;
    d_base = 0;
    d_dlvl = 0;
    d_rlvl = Utility::maxlong ();
    Object::dref (p_os);
    p_os = nilp;
    unlock ();
  }

  // set the logger info

  void Logger::setinfo (const String& info) {
    wrlock ();
    d_info = info;
    unlock ();
  }

  // get the logger info
  
  String Logger::getinfo (void) const {
    rdlock ();
    String result = d_info;
    unlock ();
    return result;
  }

  // return the log length

  long Logger::length (void) const {
    rdlock ();
    long result = d_mcnt;
    unlock ();
    return result;
  }

  // add message with a default level

  void Logger::add (const String& mesg) {
    wrlock ();
    try {
      add (mesg, d_dlvl);
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // add a message in the logger by log level

  void Logger::add (const String& mesg, const long mlvl) {
    wrlock ();
    try {
      // save the message
      p_mlog[d_mpos].set (mesg, mlvl);
      // update position
      d_mpos = (d_mpos + 1) % d_size;
      // compute new indexes
      if (d_mcnt < d_size) {
	d_mcnt++;
      } else {
	d_base = (d_base + 1) % d_size;
      }
      // write on the output stream only at the report level
      if ((p_os != nilp) && (mlvl <= d_rlvl)) {
	p_os->writeln (getfull (d_mcnt-1));
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a message level by index

  long Logger::getmlvl (const long index) const {
    rdlock ();
    if ((index < 0) || (index >= d_mcnt)) {
      unlock ();
      throw Exception ("index-error", "index is out of range");
    }
    // compute position
    long pos = (index + d_base) % d_size;
    // get result
    long result = p_mlog[pos].d_mlvl;
    unlock ();
    return result;
  }

  // get a message time by index

  t_long Logger::gettime (const long index) const {
    rdlock ();
    try {
      if ((index < 0) || (index >= d_mcnt)) {
	throw Exception ("index-error", "index is out of range");
      }
      // compute position
      long pos = (index + d_base) % d_size;
      // get result
      t_long result = p_mlog[pos].d_time;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a message by index

  String Logger::getmesg (const long index) const {
    rdlock ();
    try {
      if ((index < 0) || (index >= d_mcnt)) {
	throw Exception ("index-error", "index is out of range");
      }
      // compute position
      long pos = (index + d_base) % d_size;
      // get result
      String result = p_mlog[pos].d_mesg;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get a fully formatted message by index

  String Logger::getfull (const long index) const {
    rdlock ();
    try {
      // get the date from the time
      Date date = gettime (index);
      // get the message
      String mesg = getmesg (index);
      // format the message
      String result = "[";
      result += date.toiso (true);
      result += "] ";
      if (d_info.isnil () == false) {
	result += d_info;
	result += ": ";
      }
      result += mesg;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // set the default level

  void Logger::setdlvl (const long dlvl) {
    wrlock ();
    d_dlvl = dlvl;
    unlock ();
  }

  // get the default level

  long Logger::getdlvl (void) const {
    rdlock ();
    long result = d_dlvl;
    unlock ();
    return result;
  }

  // set the report level

  void Logger::setrlvl (const long rlvl) {
    wrlock ();
    d_rlvl = rlvl;
    unlock ();
  }

  // get the report level

  long Logger::getrlvl (void) const {
    rdlock ();
    long result = d_rlvl;
    unlock ();
    return result;
  }

  // set the logger output stream

  void Logger::setos (Output* os) {
    wrlock ();
    Object::iref (os);
    Object::dref (p_os);
    p_os = os;
    unlock ();
  }

  // set the logger output by name

  void Logger::setos (const String& name) {
    wrlock ();
    try {
      // bind the output stream
      Object::dref (p_os); p_os = nilp;
      Object::iref (p_os = new OutputFile (name));
      // set the default mode
      p_os->setemod (LOG_MODE_DEF);      
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // resize this message log

  void Logger::resize (const long size) {
    wrlock ();
    // check the new size
    if (size < d_size) {
      unlock ();
      return;
    }
    // copy the old array in the new one
    s_mlog* mlog = new s_mlog[size];
    for (long i = 0; i < d_mcnt; i++) {
      long pos = (i + d_base) % d_size;
      mlog[i] = p_mlog[pos];
    }
    // finish the initialization
    for (long i = d_mcnt; i < size; i++) mlog[i].reset ();
    // clean and update indexes
    delete [] p_mlog;
    p_mlog = mlog;
    d_size = size;
    d_mpos = d_mcnt;
    d_base = 0;
    unlock ();
  }

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

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

  // the object supported quarks
  static const long QUARK_ADD     = zone.intern ("add");
  static const long QUARK_RESET   = zone.intern ("reset");
  static const long QUARK_SETOS   = zone.intern ("set-output-stream");
  static const long QUARK_LENGTH  = zone.intern ("length");
  static const long QUARK_RESIZE  = zone.intern ("resize");
  static const long QUARK_SETINFO = zone.intern ("set-info");
  static const long QUARK_GETINFO = zone.intern ("get-info");
  static const long QUARK_SETDLVL = zone.intern ("set-default-level");
  static const long QUARK_GETDLVL = zone.intern ("get-default-level");
  static const long QUARK_SETRLVL = zone.intern ("set-report-level");
  static const long QUARK_GETRLVL = zone.intern ("get-report-level");
  static const long QUARK_GETMESG = zone.intern ("get-message");
  static const long QUARK_GETFULL = zone.intern ("get-full-message");
  static const long QUARK_GETMTIM = zone.intern ("get-message-time");
  static const long QUARK_GETMLVL = zone.intern ("get-message-level");

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

    // check 0 argument
    if (argc == 0) return new Logger;
    // check 1 argument
    if (argc == 1) {
      Object* obj = argv->get (0);
      // check for an integer
      Integer* iobj = dynamic_cast <Integer*> (obj);
      if (iobj !=nilp) {
	long size = iobj->tointeger ();
	return new Logger (size);
      }
      // check for a string
      String* sobj = dynamic_cast <String*> (obj);
      if (sobj !=nilp) {
	return new Logger (*sobj);
      }
      throw Exception ("type-error", "invalid object with logger",
		       Object::repr (obj));
    }
    // check for 2 arguments
    if (argc == 2) {
      long   size = argv->getint (0);
      String info = argv->getstring (1);
      return new Logger (size, info);
    }
    throw Exception ("argument-error", "too many argument for logger");
  }

  // return true if the given quark is defined
  
  bool Logger::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Object::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }

  // apply this object class with a set of arguments and a quark
  
  Object* Logger::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_GETINFO) return new String  (getinfo ());
      if (quark == QUARK_GETDLVL) return new Integer (getdlvl ());
      if (quark == QUARK_GETRLVL) return new Integer (getrlvl ());
      if (quark == QUARK_RESET) {
	reset ();
	return nilp;
      }
    }
    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_ADD) {
	String mesg = argv->getstring (0);
	add (mesg);
	return nilp;
      }
      if (quark == QUARK_SETINFO) {
	String info = argv->getstring (0);
	setinfo (info);
	return nilp;
      }
      if (quark == QUARK_GETMESG) {
	long index = argv->getint (0);
	return new String (getmesg (index));
      }
      if (quark == QUARK_GETFULL) {
	long index = argv->getint (0);
	return new String (getfull (index));
      }
      if (quark == QUARK_GETMTIM) {
	long index = argv->getint (0);
	return new Integer (gettime (index));
      }
      if (quark == QUARK_GETMLVL) {
	long index = argv->getint (0);
	return new Integer (getmlvl (index));
      }
      if (quark == QUARK_SETDLVL) {
	long dlvl = argv->getint (0);
	setdlvl (dlvl);
	return nilp;
      }
      if (quark == QUARK_SETRLVL) {
	long rlvl = argv->getint (0);
	setrlvl (rlvl);
	return nilp;
      }
      if (quark == QUARK_RESIZE) {
	long size = argv->getint (0);
	resize (size);
	return nilp;
      }
      if (quark == QUARK_SETOS) {
	Object* obj = argv->get (0);
	// check for an output stream
	Output* os = dynamic_cast <Output*> (obj);
	if (os != nilp) {
	  setos (os);
	  return nilp;
	}
	// check for a string
	String* sobj = dynamic_cast <String*> (obj);
	if (sobj != nilp) {
	  setos (*sobj);
	  return nilp;
	}
	throw Exception ("type-error", "invalid object set-output-stream",
			 Object::repr (obj));
      }
    }
    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_ADD) {
	String mesg = argv->getstring (0);
	long   mlvl = argv->getint    (1);
	add (mesg, mlvl);
	return nilp;
      }
    }
    // apply these arguments with the object
    return Object::apply (robj, nset, quark, argv);
  }
}
