// ---------------------------------------------------------------------------
// - Mac.cpp                                                                 -
// - afnix:sec module - base mac 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-2019 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Mac.hpp"
#include "Byte.hpp"
#include "Ascii.hpp"
#include "Vector.hpp"
#include "Unicode.hpp"
#include "Integer.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"

namespace afnix {

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

  // create a mac by name and key

  Mac::Mac (const String& name, const Key& mkey) {
    // check for valid key
    if (mkey.ismk () == false) {
      throw Exception ("mac-error", "invalid key in mac constructor");
    }
    d_name = name;
    d_mkey = mkey;
  }


  // return the class name

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

  // return the mac name

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

  // return the mac key

  Key Mac::getkey (void) const {
    rdlock ();
    try {
      Key result = d_mkey;
      unlock ();
      return result;
    } catch (...) {
      unlock ();
      throw;
    }
  }

  // derive a message mac from an octet string

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

  String Mac::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 mac from a buffer

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

  // compute a message mac from an input stream

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

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

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

  // the mac supported quarks
  static const long QUARK_RESET   = zone.intern ("reset");
  static const long QUARK_LENGTH  = zone.intern ("length");
  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_GETKEY  = zone.intern ("get-key");
  static const long QUARK_GETBYTE = zone.intern ("get-byte");

  // return true if the given quark is defined

  bool Mac::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Nameable::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }
  
  // apply this object with a set of arguments and a quark
  
  Object* Mac::apply (Runnable* robj, 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_FORMAT)  return new String  (format  ());
      if (quark == QUARK_GETKEY)  return new Key     (getkey  ());
      if (quark == QUARK_LENGTH)  return new Integer (length  ());
      if (quark == QUARK_RESET) {
	reset ();
	return nullptr;
      }
    }
    // check for 1 argument
    if (argc == 1) {
      if (quark == QUARK_GETBYTE) {
	long index = argv->getlong (0);
	return new Byte (getbyte (index));
      }
      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 != nullptr) {
	  String msg = lval->tostring ();
	  return new String (compute (msg));
	}
	// check for a buffer
	Buffer* bval = dynamic_cast <Buffer*> (obj);
	if (bval != nullptr) return new String (compute (*bval));
	// check for an input stream
	InputStream* is = dynamic_cast <InputStream*> (obj);
	if (is != nullptr) return new String (compute (*is));
	// invalid object
	throw Exception ("type-error", "invalid object for mac compute",
			 Object::repr (obj));
      }
    }
    // call the nameable method
    return Nameable::apply (robj, nset, quark, argv);
  }
}
