#include <Xm/Xm.h>
#include <stdio.h>
#include <stdlib.h>
#include <Xm/PushB.h>
#include <Xm/TextF.h>
#include <Xm/Form.h>
#include <XmHTML/XmHTML.h>
#include "easysock.h"
#include "url_manipulation.h"

void testFunc(Widget,XtPointer,XmPushButtonCallbackStruct *);

int main(int argc,char** argv) {
	Widget window,top_wid,search_bar,search,result;
	XtAppContext app;
	top_wid = XtVaAppInitialize(&app,
			"Web Browser",
			NULL,0,&argc,argv,NULL,NULL);

	window = XtVaCreateManagedWidget("Main Window",
					xmFormWidgetClass,
					top_wid,
					NULL);

	search = XtVaCreateManagedWidget("Search",
					xmPushButtonWidgetClass,
					window,
					XmNtopAttachment,XmATTACH_FORM,
					XmNrightAttachment,XmATTACH_FORM,
					NULL);

	search_bar = XtVaCreateManagedWidget("Search Bar",
					xmTextFieldWidgetClass,
					window,
					XmNleftAttachment,XmATTACH_FORM,
					XmNtopAttachment,XmATTACH_FORM,
					XmNrightAttachment,XmATTACH_WIDGET,XmNrightWidget,search,NULL);


	result = XtVaCreateManagedWidget("HTML Result",
					xmHTMLWidgetClass,
					window,
					XmNbottomAttachment,XmATTACH_FORM,
					XmNrightAttachment,XmATTACH_FORM,
					XmNleftAttachment,XmATTACH_FORM,
					XmNtopAttachment,XmATTACH_WIDGET,XmNtopWidget,search_bar,NULL);

	int val = 5;
	Widget widget_array[] = {search_bar,result};
	XtAddCallback(search,XmNactivateCallback,testFunc,widget_array);



	
	XtRealizeWidget(top_wid);
	XtAppMainLoop(app);
	
}

void testFunc(Widget w, XtPointer client_data, XmPushButtonCallbackStruct *callback_struct) {
	Widget* widget_list = (Widget *)client_data;
	Widget result_widget = widget_list[1];
	Widget text_widget = widget_list[0];
	int port;

	char* url = XmTextFieldGetString(text_widget);

	char* protocol = url_to_proto(url); /* Extract the protocol string from the URL input */

	if (strcmp(protocol,"http") == 0) {
		port = 80;
	} else if (strcmp(protocol,"https") == 0) {
		port = 443;
	} else {
		exit(50); /* I haven't added support for other protocols yet */
	}
	
	/* We call the create_remote function to create an address, bind it to a socket,
	and make the connection for us. It returns the socket, so that the HTTP request can be made.
	First parameter is IP version - set to -1 because we don't know yet if the address is IPv4 or IPv6. */

	struct sockaddr* address_struct;
	int remote_socket = create_remote(-1,'T',url_to_hostname(url),port,address_struct);
	
	

	XmHTMLTextSetString(result_widget,"");
//	printf("%d\n",val);
//	exit(2);
}