/*
	Main plugin module
*/

#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<ctype.h>
#include	<fcntl.h>
#include	<errno.h>
#include	<time.h>

/*
#define MYDEBUG	1	// turn on debug output
#define KDEBUG		1	// use serial debugging
*/
#include "mdebug.h"

#ifdef __MAXON__
#include <pragma/exec_lib.h>
#else
#include <proto/exec.h>    // all other compilers
#endif

#include "plugins/plugins.h"
#include "ezhttp/ezhttp.h"

#include "proto/ezhttp.h"


struct EZHTTPBase			*EZHTTPBase;


const UBYTE	pl_modname[]		= LIBN;
const UBYTE	pl_name[]			= "EZP Test PlugIn";
ULONG			pl_msglength		= 140;
const UBYTE	pl_url[]				= "http://www.foobar.com";

const UBYTE	pl_tcode[]			= "+49";

// This plugin is meant to send messages to mobile phones
UBYTE			pl_rectype			= RECTYPE_MOBILE;

// This plugin requires a username and a password to log in
ULONG			pl_flags				= PINFO_USERNAME | PINFO_PASSWORD;

const UBYTE *homepage			= "www.foobar.com";


struct my_job {
	UBYTE *mj_fqnumber;
	UBYTE *mj_message;
	UBYTE *mj_originator;
	UBYTE *mj_username;
	UBYTE *mj_password;
	UWORD mj_maxchars;
};


/* local protos */

ULONG		connect_service(struct my_job *);


ULONG SAVEDS ASM PL_ProcessMessageA(REG(a0) APTR Handle, REG(a1) struct TagItem *TagList)
{
	struct my_job mjob;
	struct TagItem *tagitem;
	ULONG result;

	mjob.mj_fqnumber		=
	mjob.mj_message		=
	mjob.mj_originator	=
	mjob.mj_username		=
	mjob.mj_password		= NULL;
	mjob.mj_maxchars		= pl_msglength;

	// We need at least ezhttp.library V4.x
	//
	if (!(EZHTTPBase = (struct EZHTTPBase *)OpenLibrary(EZHTTPNAME".library", 4)))
		return PLERR_CALL_FAILED;

	// Now let's try to get everything from EZP we need to create and send the
	// message
	if (tagitem = TagList) {
		for (; tagitem->ti_Tag != TAG_DONE; tagitem++) {

			switch (tagitem->ti_Tag) {
			case PM_FQNUMBER		:
				mjob.mj_fqnumber		= (UBYTE *)tagitem->ti_Data;
				break;
			case PM_CNVMESSAGE	:
				mjob.mj_message		= (UBYTE *)tagitem->ti_Data;
				break;
			case PM_ORIGINATOR	:
				mjob.mj_originator	= (UBYTE *)tagitem->ti_Data;
				break;
			case PM_USERNAME		:
				mjob.mj_username		= (UBYTE *)tagitem->ti_Data;
				break;
			case PM_PASSWORD		:
				mjob.mj_password		= (UBYTE *)tagitem->ti_Data;
				break;
			case PM_MAXCHARS		:
				mjob.mj_maxchars		= (UWORD)tagitem->ti_Data;
				break;
			}
		}
	}

	D(bug("   FQNumber  : %ls\n", mjob.mj_fqnumber));
	D(bug("   Originator: %ls\n", mjob.mj_originator));
	D(bug("   UserName  : %ls\n", mjob.mj_username));
	D(bug("   Password  : %ls\n", mjob.mj_password));
	D(bug("   MaxChars  : %ld\n", mjob.mj_maxchars));

	//
	// Send SMS
	//
	result = connect_service(&mjob);

	if (result == PLERR_RETURN_OK) {
		D(bug("HTTP requests succeeded\n"));
	}
	else {
		D(bug("HTTP requests failed with %ld!\n", result));
	}

	CloseLibrary((struct Library *)EZHTTPBase);

	return (result);
}

ULONG SAVEDS ASM PL_GetAttrA(REG(a0) APTR Handle, REG(a1) struct TagItem *TagList)
{
	struct TagItem *tagitem = TagList;
	LONG *value;
	ULONG numProcessed = 0;

	if (!TagList)
		return 0;

	//
	// Process TagList if available
	//
	for (; tagitem->ti_Tag != TAG_DONE; tagitem++) {
		value = (LONG *)tagitem->ti_Data;

		switch (tagitem->ti_Tag) {
		case PL_NAME				:
			*value = (ULONG)pl_name;
			++numProcessed;
			break;
		case PL_TCODE				:
			*value = (ULONG)pl_tcode;
			++numProcessed;
			break;
		case PL_MSGLENGTH			:
			*value = (ULONG)pl_msglength;
			++numProcessed;
			break;
		case PL_URL					:
			*value = (ULONG)pl_url;
			++numProcessed;
			break;
		case PL_FLAGS				:
			*value = (ULONG)pl_flags;
			++numProcessed;
			break;
		case PL_RECTYPE			:
			*value = (UBYTE)pl_rectype;
			++numProcessed;
			break;
		}
	}

	return (numProcessed);
}

ULONG connect_service(struct my_job *mjob)
{
	APTR http;
	ULONG success, redirected;
	UBYTE *pagename, *redirect, *location;
	ULONG res;
	ULONG result	= PLERR_PROTOCOL_FAILED;

	if (!mjob->mj_message)
		return PLERR_CALL_FAILED;

	// First we create a HTTP object
	//
	if (!(http = HL_NewObject(0,
			HT_MODNAME,		pl_modname,
			HT_REFERER,		FALSE,
			HT_USERAGENT,	"Mozilla/4.7 [en] (Win98; I)",
			TAG_DONE))) {
		result = PLERR_CALL_FAILED;
		goto safeexit;
	}

	// Now we try to get the main homepage...
	//
	HL_DoMethod(http, HM_GET,
			HT_URI_COPY,	(UBYTE *)homepage,
			TAG_DONE);

	// ...and some attributes about this request
	//
	res = HL_GetAttrs(http,
			HL_SUCCESS,			&success,
			HL_PAGENAME,		&pagename,
			HL_REDIRECTED,		&redirected,
			HL_REDIRECT,		&redirect,
			HL_LOCATION,		&location,
			TAG_DONE);

	if (res != 5) {
		D(bug("Couldn't get all necessary attrs (%ld)\n", res));
		goto safeexit;
	}

	if (success) {
		D(bug("Page was loaded successfully\n"));

		if (pagename) {
			D(bug("Temporary page name: \"%ls\"\n", pagename));
		}

		if (redirected) {
			char *hdhost, *path;

			if (location) {
				D(bug("Location: \"%ls\"\n", location));
			}

			D(bug("We got redirected to: \"%ls\"\n", redirect));

			// Now we try to get the host part of the address we got redirected to
			hdhost = HL_HostPart(redirect);

			if (hdhost) {
				D(bug("HostPart: \"%ls\"\n", hdhost));
			}
			else {
				D(bug("No HostPart in : \"%ls\"\n", redirect));
			}

			if (path = HL_PathPart(redirect)) {
				D(bug("PathPart: \"%ls\"\n", path));
				HL_FreeString(path);
			}
			if (path = HL_FilePart(redirect)) {
				D(bug("FilePart: \"%ls\"\n", path));
				HL_FreeString(path);
			}

			if (hdhost) {
				// Get SMS page now
				//
				HL_DoMethod(http, HM_GET,
						HT_URI,		HL_VStrDup("%ls/%ls", (UBYTE *)hdhost, "smsfree.jsp"),
						TAG_DONE);

				// Get attributes about this request
				//
				HL_GetAttrs(http,
						HL_SUCCESS,	&success,
						TAG_DONE);

				if (success) {
					// Adjust counter
					int counter = mjob->mj_maxchars - strlen(mjob->mj_message);

					D(bug("SMS page was loaded successfully\n"));

					// Send SMS now
					//
					// This is nothing else than posting a form with all necessary
					// fields the SMS gateway expects
					//
					HL_DoMethod(http, HM_POST,
							HT_URI,		HL_VStrDup((UBYTE *)"%ls/%ls", hdhost, "smssend.jsp"),
							HT_AVP,		HL_GetAVP("Action",			AVP_CONV,	"create"),
							HT_AVP,		HL_GetAVP("Number",			AVP_CONV,	mjob->mj_fqnumber),
							HT_AVP,		HL_GetAVP("sms",				AVP_CONV,	mjob->mj_message),
							HT_AVP,		HL_GetAVP("Chars",			AVP_CONV,	"%ld", counter),
							TAG_DONE);

					// Get attributes about this request
					//
					HL_GetAttrs(http,
							HL_SUCCESS,		&success,
							HL_PAGENAME,	&pagename,
							TAG_DONE);

					if (success) {
						D(bug("SMS has been sent successfully :)\n"));

						//
						// Here we could load and parse the result page (pagename)
						// to see if it contains some kind of positive/negative
						// response to our post.
						//

						// Log this message transfer as beeing successful.
						result = PLERR_RETURN_OK;
					}
					else {
						D(bug("Couldn't send SMS :(\n"));
					}
				}
				else {
					D(bug("Couldn't get SMS page\n"));
				}
			}

			HL_FreeString(hdhost);
		}
		else {
			D(bug("We didn't get redirected\n"));
		}
	}
	else {
		D(bug("Couldn't get home page: %ls\n", homepage));
		goto safeexit;
	}

safeexit:
	// We only use and return TCP errors if the SMS transfer wasn't
	// successful.
	// Otherwise we ignore any TCP error.
	//
	if (result != PLERR_RETURN_OK) {
		ULONG tcpres;

		if (HL_GetAttrs(http,
				HL_TCPRES,	&tcpres,
				TAG_DONE))
			if (tcpres != HLERR_RETURN_OK)
				result = tcpres;
	}

	HL_DisposeObject(http);

	return (result);
}