// ---------------------------------------------------------------------------
// - Hasher.cpp                                                              -
// - afnix:sec module - base message hasher 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-2011 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Byte.hpp"
#include "Ascii.hpp"
#include "Vector.hpp"
#include "Hasher.hpp"
#include "Unicode.hpp"
#include "Boolean.hpp"
#include "Integer.hpp"
#include "Cryptics.hxx"
#include "QuarkZone.hpp"
#include "Exception.hpp"

namespace afnix {

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

  // create a hasher by name and size

  Hasher::Hasher (const String& name, const long size, 
		  const long hlen) : BlockBuffer (size) {
    // check for size
    if (hlen <= 0) {
      throw Exception ("size-error", "invalid hasher size in constructor");
    }
    // initialize hasher
    d_name = name;
    d_hlen = hlen;
    d_rlen = d_hlen;
    p_hash = new t_byte[d_hlen];
    reset ();
  }

  // create a hasher by name, size and result length

  Hasher::Hasher (const String& name, const long size, const long hlen,
		  const long rlen) : BlockBuffer (size) {
    // check for size
    if ((hlen <= 0) || (rlen <= 0) || (rlen > hlen)) {
      throw Exception ("size-error", "invalid hasher size in constructor");
    }
    // initialize hasher
    d_name = name;
    d_hlen = hlen;
    d_rlen = rlen;
    p_hash = new t_byte[d_hlen];
    reset ();
  }

  // destroy this hasher
  
  Hasher::~Hasher (void) {
    delete [] p_hash;
  }

  // return the class name

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

  // reset this hasher buffer

  void Hasher::reset (void) {
    wrlock ();
    try {
      BlockBuffer::reset ();
      for (long i = 0; i < d_hlen; i++) p_hash[i] = nilc;
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the hasher name

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


  // return the hash value length

  long Hasher::gethlen (void) const {
    rdlock ();
    try {
      long result = d_hlen;
      unlock ();
      return result;    
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // return the hash result length

  long Hasher::getrlen (void) const {
    rdlock ();
    try {
      long result = d_rlen;
      unlock ();
      return result;    
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the hash value by index

  t_byte Hasher::getbyte (const long index) const {
    rdlock ();
    try {
      if (index >= d_rlen) {
	throw Exception ("index-error", "hash index is out of bound");
      }
      t_byte result = p_hash[index];
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the hash value as a relatif

  Relatif Hasher::gethval (void) const {
    rdlock ();
    try {
      Relatif result (p_hash, d_hlen);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // get the hash result as a relatif

  Relatif Hasher::getrval (void) const {
    rdlock ();
    try {
      Relatif result (p_hash, d_rlen);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // derive a message hasher from an octet string

  String Hasher::derive (const String& s) {
    long    size = 0;
    t_byte* sbuf = Unicode::stob (size, s);
    wrlock ();
    try {
      reset   ();
      process (sbuf, size);
      finish  ();
      String result = format ();
      delete [] sbuf;
      unlock ();
      return result;
    } catch (...) {
      delete [] sbuf;
      unlock ();
      throw;
    }
  }
  
  // compute a message hasher from a string

  String Hasher::compute (const String& msg) {
    char* cbuf = Unicode::encode (Encoding::UTF8, msg);
    long  size = Ascii::strlen (cbuf);
    wrlock ();
    try {
      reset   ();
      process ((t_byte*) cbuf, size);
      finish  ();
      String result = format ();
      delete [] cbuf;
      unlock ();
      return result;
    } catch (...) {
      delete [] cbuf;
      unlock ();
      throw;
    }
  }

  // compute a message hasher from a buffer

  String Hasher::compute (Buffer& buf) {
    wrlock ();
    try {
      reset   ();
      process (buf);
      finish  ();
      String result = format ();
      unlock  ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // compute a message hasher from an input stream

  String Hasher::compute (InputStream& is) {
    wrlock ();
    try {
      reset   ();
      process (is);
      finish  ();
      String result = format ();
      unlock  ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // check if the string is a valid hash value

  bool Hasher::ishash (const String& s) const {
    rdlock ();
    try {
      bool result = ishhs (s, d_rlen * 2);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // format the message hash
  
  String Hasher::format (void) const {
    rdlock ();
    try {
      String result = Ascii::btos (p_hash, d_rlen);
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // process a message by data

  void Hasher::process (const t_byte* msg, const long size) {
    wrlock ();
    try {
      long blen = size;
      while (blen != 0) {
	long step = copy ((char*) msg, blen);
	if (full () == true) update ();
	msg  += step;
	blen -= step;
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // process a message with a buffer

  void Hasher::process (Buffer& buf) {
    wrlock ();
    try {
      while (buf.empty () == false) {
	copy (buf);
	if (full () == true) update ();
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // process a message with an input stream

  void Hasher::process (InputStream& is) {
    wrlock ();
    try {
      while (is.valid () == true) {
	copy (is);
	if (full () == true) update ();
      }
      unlock ();
    } catch (...) {
      unlock ();
      throw;
    }
  }
  
  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

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

  // the hasher supported quarks
  static const long QUARK_RESET   = zone.intern ("reset");
  static const long QUARK_HASHP   = zone.intern ("hash-p");
  static const long QUARK_FORMAT  = zone.intern ("format");
  static const long QUARK_DERIVE  = zone.intern ("derive");
  static const long QUARK_COMPUTE = zone.intern ("compute");
  static const long QUARK_GETBYTE = zone.intern ("get-byte");
  static const long QUARK_GETHLEN = zone.intern ("get-hash-length");
  static const long QUARK_GETHVAL = zone.intern ("get-hash-value");
  static const long QUARK_GETRLEN = zone.intern ("get-result-length");
  static const long QUARK_GETRVAL = zone.intern ("get-result-value");

  // return true if the given quark is defined

  bool Hasher::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 block buffer class
    if (result == false) {
      result = hflg ? BlockBuffer::isquark (quark, hflg) : false;
    }
    unlock ();
    return result;
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* Hasher::apply (Runnable* robj, Nameset* nset, const long quark,
			 Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();
    
    // check for 0 argument
    if (argc == 0) {
      if (quark == QUARK_FORMAT)  return new String  (format  ());
      if (quark == QUARK_GETHLEN) return new Integer (gethlen ());
      if (quark == QUARK_GETHVAL) return new Relatif (gethval ());
      if (quark == QUARK_GETRLEN) return new Integer (getrlen ());
      if (quark == QUARK_GETRVAL) return new Relatif (getrval ());
      if (quark == QUARK_RESET) {
	reset ();
	return nilp;
      }
    }

    // check for 1 argument
    if (argc == 1) {
      if (quark == QUARK_GETBYTE) {
	long index = argv->getlong (0);
	return new Byte (getbyte (index));
      }
      if (quark == QUARK_HASHP) {
	String s = argv->getstring (0);
	return new Boolean (ishash (s));
      }
      if (quark == QUARK_DERIVE) {
	String s = argv->getstring (0);
	return new String (derive (s));
      }
      if (quark == QUARK_COMPUTE) {
	Object* obj = argv->get (0);
	// check for a literal
	Literal* lval = dynamic_cast <Literal*> (obj);
	if (lval != nilp) {
	  String msg = lval->tostring ();
	  return new String (compute (msg));
	}
	// check for a buffer
	Buffer* bval = dynamic_cast <Buffer*> (obj);
	if (bval != nilp) return new String (compute (*bval));
	// check for an input stream
	InputStream* is = dynamic_cast <InputStream*> (obj);
	if (is != nilp) return new String (compute (*is));
	// invalid object
	throw Exception ("type-error", "invalid object for hasher compute",
			 Object::repr (obj));
      }
    }
    // check the nameable class
    if (Nameable::isquark (quark, true) == true) {
      return Nameable::apply (robj, nset, quark, argv);
    }
    // fallback with the block buffer method
    return BlockBuffer::apply (robj, nset, quark, argv);
  }
}
