#include ".\pythoninclude\Python.h"
#include <Windows.h>
#include "loading.h"
#include "scripts.h"
#include "engine.h"
#pragma warning( disable : 701 127 )



void Load_Module(const char* filename) // filename should be module_name
{
	PyObject *pName, *pModule, *pFunc, *pTemp;

    pName = PyUnicode_FromString(filename);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
	pTemp = pModule;
	Py_XINCREF(pTemp);
	ModulesArray[ModulesArrayIndex++] = pTemp;
    Py_DECREF(pName);

	 if (pModule != NULL) 
	{

		if (PyObject_HasAttrString(pModule, "OnLoad")) {
			pFunc = PyObject_GetAttrString(pModule, "OnLoad");
			 /* pFunc is a new reference */

			if (pFunc && PyCallable_Check(pFunc)) 
			{			
            PyObject_CallObject(pFunc, NULL);
			}
			else 
			{
				if (PyErr_Occurred())
				{
					PyErr_Print();
				}
			}
		}
        Py_XDECREF(pFunc);
       // Py_DECREF(pModule);
    }
    else 
	{
        PyErr_Print();
        printf("Failed to load \"%s\"\n", filename);
    }
}

void Load_All_Modules()
{

	memset((void *)ModulesArray, 0, 256*sizeof(PyObject*));
	ModulesArrayIndex = 0;
	char basepath[256], initpyfile[256]; // changed this a little bit
	GetCurrentDirectory(128, basepath);
	char pluginsdir[256];
	sprintf(pluginsdir, "%s\\PythonPlugins", basepath);
	
	sprintf(initpyfile, "%s\\PythonPlugins\\__init__.py", basepath);
	FILE* initpy = fopen(initpyfile, "r");
	if (initpy == NULL)
	{	
		printf("\nFile \"__init.py__\" doesn't exist! Creating file....\n\n"); 
		initpy = fopen(initpyfile,"w+");
	}
	fclose(initpy);


	wchar_t python_paths[1024];
	swprintf(python_paths, 1024, L"C:\\Windows\\system32\\python32.zip;C:\\Python32\\DLLs;C:\\Python32\
\lib;C:\\Python32;C:\\Python32\\lib\\site-packages;%ls;", CharToWideChar(pluginsdir));
	wprintf(L"%ls", python_paths);
	Py_SetPath(python_paths); //Hardcode the paths this Python plugin uses and add the dir with the .py plugins in it
	sprintf(pluginsdir, "%s\\PythonPlugins\\*", basepath);

	char *plugins[256];
	memset((void *)plugins, 0, 256*4);
	GetFiles(pluginsdir, plugins, 256);

	if ( (!plugins) || (( strcmp((char*)plugins[0], "__init__") == 0) && !plugins[1]) )
	{
		MessageBox(HWND_DESKTOP,"No valid Python files found inside the PythonPlugins directory, shutting down FDS.","SSGM Python Plugin Error",MB_OK|MB_ICONEXCLAMATION);
		ExitProcess(0);
	}
	for(int i = 0; i < 256; i++)
	{	
		char *x = plugins[i];
		if(!x )
		{
			continue;			
		}
		if ( (strcmp(x, "__init__") == 0))
		{
			continue;
		}

		std::string modulename = "PythonPlugins.";
		modulename+= x;
		Load_Module(modulename.c_str());		
		delete []x;
	}
}

void GetFiles(const char *Path, char **Data, int DataLength)
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = INVALID_HANDLE_VALUE;

	hFind = FindFirstFile(Path, &FindFileData);
	if(FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
	{
		char *file = new char[strlen(FindFileData.cFileName)+1];
		char *buffer = new char[strlen(FindFileData.cFileName)-2];
		strcpy(file, FindFileData.cFileName);
		for(int i = 0; i < DataLength; i++)
		{
			if(!Data[i])
			{
				sscanf(file, "%[^'.']", buffer);
				delete[] file;
				Data[i] = buffer;
				break;
			}
		}
	}
	while (FindNextFile(hFind, &FindFileData) != 0) 
	{
		if(FindFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
		{
			char *file = new char[strlen(FindFileData.cFileName)+1];
			char *buffer = new char[strlen(FindFileData.cFileName)-2];
			strcpy(file, FindFileData.cFileName);
			for(int i = 0; i < DataLength; i++)
			{
				if(!Data[i])
				{
					sscanf(file, "%[^'.']", buffer);
					delete[] file;
					Data[i] = buffer;
					break;
				}
			}
		}
	}
	FindClose(hFind);
}