/* Metallurgy - Higher Level Interface to Chordata
 * Copyright (C) 2001-2002  Jay Freeman (saurik)
*/

/*
 *        Redistribution and use in source and binary
 * forms, with or without modification, are permitted
 * provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the
 *    above copyright notice, this list of conditions
 *    and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions
 *    and the following disclaimer in the documentation
 *    and/or other materials provided with the
 *    distribution.
 * 3. The name of the author may not be used to endorse
 *    or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdafx.h"
#include "Helper.h"

#include "menes-com/Framework.h"

#include "metallurgy/Assembly.h"
#include "metallurgy/Attribute.h"
#include "metallurgy/Event.h"
#include "metallurgy/Field.h"
#include "metallurgy/Implement.h"
#include "metallurgy/MemberRef.h"
#include "metallurgy/Method.h"
#include "metallurgy/Module.h"
#include "metallurgy/ModuleRef.h"
#include "metallurgy/Param.h"
#include "metallurgy/Property.h"
#include "metallurgy/StandAlone.h"
#include "metallurgy/Token.h"
#include "metallurgy/TokenList.h"
#include "metallurgy/TypeDef.h"
#include "metallurgy/TypeRef.h"
#include "metallurgy/TypeSpec.h"

#include "chordata/chordata.h"
#include "chordata/IMetaDataDispenser.h"

#include "chordata/Result.h"
using namespace Chordata::Result;

#include "chordata/Tokens.h"
using namespace Chordata::Tokens;

#include "chordata/Utils.h"
using namespace Chordata::Utils;

#include "filet/PE.h"

namespace Metallurgy {

Module::Module(const std::wstring &path, const Assembly *assembly) :
	ModuleToken(this, 0x00000001),
	typedefs(NULL),
	path(path)
{
	this->assembly = assembly;
	tokens.insert(TokenMap::value_type(token, this));

    mmap.open(path);

	Diapexis::Handle<Chordata::IMetaDataDispenser> dispenser;
	Diapexis::PexCreateInstance(_idof(Chordata::Microsoft::Dispenser), _idof(Chordata::IMetaDataDispenser), (void **) &dispenser.Mend());
	dispenser->OpenScopeOnMemory(mmap.begin(), mmap.size(), 0, _idof(Chordata::IMetaDataImport), (Diapexis::Unknown **) &import.Mend());

	if (import == NULL)
		throw std::wstring(L"This file does not contain any metadata.");

	dos	= (Filet::Headers::DOS *)	mmap.begin();
	nt	= (Filet::Headers::NT32 *)	((uint8_t *) dos + dos->e_lfanew);

	wchar_t buff[1024];

	import->GetScopeProps(buff, 1024, NULL, &vid);

	name = buff;
}

Module::~Module() {
	delete typedefs;
	for (TokenMap::iterator token = tokens.begin(); token != tokens.end(); token++)
		if (token->second != this)
			delete token->second;
}

Chordata::IMetaDataImport *Module::operator ->() const {
	return import;
}

Chordata::IMetaDataImport *Module::getImport() const {
	return import;
}

void *Module::FindRVA(uint32_t rva) const {
	return Filet::Utils::ImageRvaToVa(nt, dos, rva, NULL);
}

ModuleToken *Module::ResolveToken(Chordata::Token token) const {
	if (TokenIsNil(token))
		return NULL;

	TokenMap::const_iterator item = tokens.find(token);
	if (item != tokens.end())
		return dynamic_cast<ModuleToken *>(item->second);

	if (!import->IsValidToken(token))
		throw std::wstring(L"Completely bogus corrupted token value.  I blame Microsoft.");

	ModuleToken *unit = NULL;
	switch (GetTokenType(token)) {
		case mdtCustomAttribute:
			unit = new Attribute(this, token);
		break;
		case mdtEvent:
			unit = new Event(this, token);
		break;
		case mdtFieldDef:
			unit = new Field(this, token);
		break;
        case mdtInterfaceImpl:
			unit = new Implement(this, token);
        break;
		case mdtMemberRef:
			unit = new MemberRef(this, token);
		break;
		case mdtMethodDef:
			unit = new Method(this, token);
		break;
		case mdtModuleRef:
			unit = new ModuleRef(this, token);
		break;
		case mdtParamDef:
			unit = new Param(this, token);
		break;
		case mdtProperty:
			unit = new Property(this, token);
		break;
		case mdtSignature:
			unit = new StandAlone(this, token);
		break;
		case mdtTypeDef:
			unit = new TypeDef(this, token);
		break;
		case mdtTypeRef:
			unit = new TypeRef(this, token);
		break;
		case mdtTypeSpec:
			unit = new TypeSpec(this, token);
		break;

		default:
			::MessageBox(NULL, L"I don't know what this token is.  There are many tokens I don't process, but I also shouldn't be asking for them.  Recently, I've found that Microsoft's API is returning invalid, corrupted tokens to me.  I added checks to see if the token is valid, but the check uses Microsoft's other API which seems to think that it is a valid token.  I'm not sure what to do at this point.  If you see this dialog, please write your congressmen or other local representative and complain about the state of the world.  Another option is to drop back to Beta 2 of the .NET Framework SDK (which seemed relatively bug free over the major interfaces).  If you are using Beta 2 this dialog will not pop up as I won't get a corrupted token value.  However, as I obviously don't know what to _do_ with the token, the entire application is likely going to crash.", L"Microsoft hates me.", MB_OK);
			throw std::wstring(L"Microsoft hates me.");
			unit = new ModuleToken(this, token);
		break;
	}

	tokens.insert(TokenMap::value_type(token, unit));
	return unit;
}

std::wstring Module::getPath() const {
	return path;
}

std::wstring Module::getName() const {
	return name;
}

GUID Module::getVID() const {
	return vid;
}

std::wstring Module::getUserString(mdString token) const {
	wchar_t *buffer = (wchar_t *) malloc(1024 * sizeof(wchar_t));
	uint32_t length = 1024;
	while (import->GetUserString(token, buffer, length, &length) == Success::Truncation)
		buffer = (wchar_t *) realloc(buffer, length * sizeof(wchar_t));

	std::wstring data(buffer, length);
	free(buffer);
	return data;
}

TypeDef *Module::FindTypeDef(const std::wstring &name) const {
	mdTypeDef data = 0;
	import->FindTypeDefByName(name.c_str(), NilToken, &data);
	return dynamic_cast<TypeDef *>(ResolveToken(data));
}

TypeRef *Module::FindTypeRef(const std::wstring &name) const {
	mdTypeRef data = 0;
	import->FindTypeRef(NilToken, name.c_str(), &data);
	return dynamic_cast<TypeRef *>(ResolveToken(data));
}

Token *Module::XmlKeyLookup(const std::wstring &key) const {
	if (key.compare(0, 2, L"T:") == 0) {
		return FindTypeDef(key.substr(2));
	} else if (key.compare(0, 2, L"M:") == 0) {
	}

	return NULL;
}

TokenList Module::getFields() const {
	ENUMERATE1(mdFieldDef, this, EnumFields, Field, NilToken)
}

TokenList Module::getMethods() const {
	ENUMERATE1(mdMethodDef, this, EnumMethods, Method, NilToken)
}

TokenList Module::getModuleRefs() const {
	ENUMERATE0(mdModuleRef, this, EnumModuleRefs, ModuleRef)
}

TokenList Module::getTypeDefs() const {
	//ENUMERATE0(mdTypeDef, this, EnumTypeDefs, TypeDef)

	if (typedefs == NULL) {
		typedefs = new TokenList();

		Chordata::CorEnum henum = NULL;
		mdTypeDef datas[256];
		uint32_t count, total = 1;

		while (S_OK == import->EnumTypeDefs(&henum, datas, 256, &count) && count > 0)
			for (uint32_t i(0); i < count; i++, total++)
				typedefs->insert(dynamic_cast<TypeDef *>(ResolveToken(datas[i])));
	}

	return *typedefs;
}

TokenList Module::getTypeRefs() const {
	ENUMERATE0(mdTypeRef, this, EnumTypeRefs, TypeRef)
}

}