#ifndef __WON_CDKEY_H__
#define __WON_CDKEY_H__
#include "WONShared.h"

#include "WONCommon/ByteBuffer.h"
#include "WONCommon/RegKey.h"
#include "WONCrypt/Blowfish.h"
#include <string>

namespace WONAPI
{

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
class CDKey
{
private:
	std::string				mProduct;     // Product string
	ByteBufferPtr			mKey;         // Key value
	bool					mIsValid;

public:
	CDKey();
	explicit CDKey(const std::string& theProduct);	

	// Initialization
	bool Init(const std::string& theKey); 	// CVCN-CVCN-CVCN-CVCN-NNNN (dashes are optional)
	bool InitEncrypted(const void *theEncryptedKey, unsigned long theEncryptLen); // (init from encrypted data generated by GetEncrypted())

	// Key access
	std::string GetString() const; // string version of the key
	const ByteBuffer* GetRaw() const { return mKey; } // raw 8 byte format
	ByteBufferPtr GetEncrypted() const; // encrypted version

	// Product string 
	void SetProductString(const std::string &theProductString); // invalidates the current key
	const std::string& GetProductString() const { return mProduct; }
	
	// Validity
	bool IsValid() const { return mIsValid; }
	void Invalidate();
	bool IsBeta() const;

	// Storage
	bool SaveToRegistry(RegKeyRoot theRoot = REGKEY_LOCAL_MACHINE); // stores under SOFTWARE\WON\CDKeys\<Product>
	bool LoadFromRegistry(RegKeyRoot theRoot = REGKEY_LOCAL_MACHINE);
	void ClearFromRegistry(RegKeyRoot theRoot = REGKEY_LOCAL_MACHINE);
	bool SaveToFile(const std::string &theFileName);
	bool LoadFromFile(const std::string &theFileName);

private:
	unsigned char LightValidityCheck() const;
	bool CalcKeyFromBuffer(const char *theBuf);
	void GetSymmetricKey(Blowfish &theSymKey) const;
};


}; // namespace WONAPI

#endif
