#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <dirent.h>

#include "quickmail.h"
#include "mailFromGui.h"

#define TO          "ae-support@oni2.net"
#define SMTPSERVER  "mail.illy.bz"
#define SUBJECT     "AE support request"
#define SMTPPORT    25
#define SMTPUSER    NULL
#define SMTPPASS    NULL

static void appendString(char** buffer, unsigned int* bufsize, char* append) {
	if ((strlen(*buffer) + strlen(append) + 2) >= *bufsize) {
		unsigned int addon = (strlen(append) > 500 ? strlen(append)+500 : 500);
		*bufsize += addon;

		char* temp = malloc(*bufsize);
		
		strcpy(temp, *buffer);

		free(*buffer);
		*buffer = temp;
	}
	strcat(*buffer, append);
}

static char* buildDirectoryListing(char* path, int level) {
	unsigned int bufsize = 500;
	char* strbuf = malloc(bufsize);
	strbuf[0] = 0;
	
	if (level >= 4)
		return strbuf;
	
	struct dirent *dp;
	DIR *dfd = opendir(path);
	if(dfd != NULL) {
		while((dp = readdir(dfd)) != NULL) {
			if (strcmp(".", dp->d_name) != 0 && strcmp("..", dp->d_name) != 0) {
				char* name = malloc(strlen(path) + strlen(dp->d_name) + 2);
				sprintf(name, "%s/%s", path, dp->d_name);

				appendString(&strbuf, &bufsize, name);
				strcat(strbuf, "\n");
				
				//printf("%2d: %s\n", level, name);

				char* sub = buildDirectoryListing(name, level+1);
				appendString(&strbuf, &bufsize, sub);
			}
		}
		closedir(dfd);
	}
	return strbuf;
}

static void sendMail() {
	char message[500] = "";
	
	quickmail_initialize();
	quickmail mailobj = quickmail_create(emailFrom, SUBJECT);
	quickmail_add_to(mailobj, TO);
	if (isCCSelected) {
		quickmail_add_cc(mailobj, emailFrom);
	}
	
	if (access("AEInstaller/updater_output.log", F_OK) != 0) {
		strcat(message, "updater_output.log does not exist!\n");
	}
	if (access("AEInstaller/AEI-ProxySettings.xml", F_OK) != 0) {
		strcat(message, "AEI-ProxySettings.xml does not exist!\n");
	}

	
	quickmail_set_body(mailobj, message);
	
	quickmail_add_attachment_file(mailobj, "AEInstaller/updater_output.log", "text/plain");
	quickmail_add_attachment_file(mailobj, "AEInstaller/AEI-ProxySettings.xml", "text/xml");
	
	char* dirList = buildDirectoryListing(".", 0);
	quickmail_add_attachment_memory(mailobj, "DirListing.txt", "text/plain", dirList, strlen(dirList)+1, 1);

	const char* errmsg;
	quickmail_set_debug_log(mailobj, stderr);
	if ((errmsg = quickmail_send(mailobj, SMTPSERVER, SMTPPORT, SMTPUSER, SMTPPASS)) != NULL)
		fprintf(stderr, "Error sending e-mail: %s\n", errmsg);
	quickmail_destroy(mailobj);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	if (access("AEInstaller/", F_OK) != 0 || access("AEInstaller/AEInstaller2Updater.jar", F_OK) != 0) {
		MessageBox(NULL,
				"Please put this program in your Oni/AE folder!",
				"Invalid location",
				MB_OK | MB_ICONERROR);
	} else {
		mailFromGui(hInstance, nShowCmd);
	
		if (isSendSelected)
			sendMail();
	}
	
	return EXIT_SUCCESS;
}

