/**
 **	File ......... httpget.cpp
 **	Published ....  2006-03-27
 **	Author ....... grymse@alhem.net
**/
/*
Copyright (C) 2004  Anders Hedstrom

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
#include <HttpGetSocket.h>
#include <SocketHandler.h>
#include <Parse.h>


bool Get(const std::string& url_in,std::list<std::string>& ref)
{
	Parse pa(url_in,":/");
	std::string protocol = pa.getword();
	bool https = !strcasecmp(protocol.c_str(), "https");
	std::string host = pa.getword();
	port_t port = https ? 443 : 80;
	if (strstr(host.c_str(), ":")) // detect port from url
	{
		Parse pa(host,":");
		pa.getword();
		port = pa.getvalue();
	}
	std::string url = "/" + pa.getrest();
	std::string file; // get filename at end of url
	{
		Parse pa(url,"/");
		std::string tmp = pa.getword();
		while (tmp.size())
		{
			file = tmp;
			tmp = pa.getword();
		}
	}
	SocketHandler h;
	bool complete = false;
	std::string document;
	if (!strcasecmp(protocol.c_str(),"http") || https)
	{
		HttpGetSocket s(h, host, port, url, "");
		unsigned char *p = new unsigned char[32000]; // max doc size
		memset(p, 0, 32000);
		s.SetDataPtr(p, 31999); // preserve zero at end of document
		if (https)
		{
			s.EnableSSL();
		}
		h.Add(&s);
		h.Select(1,0);
		while (h.GetCount())
		{
			h.Select(1,0);
		}
		complete = s.Complete();
		if (complete)
		{
			document = static_cast<std::string>( (char *)s.GetDataPtr());
		}
		delete[] s.GetDataPtr();
	}
	else
	{
		printf("Unknown protocol: '%s'\n",protocol.c_str());
	}
	if (complete)
	{
		printf("%s\n", document.c_str());
	}
	return complete;
}


int main(int argc,char *argv[])
{
	for (int i = 1; i < argc; i++)
	{
		std::list<std::string> doc;
		if (!Get(argv[i], doc))
		{
			printf("Failed: %s\n",argv[i]);
		}
		else
		{
			for (std::list<std::string>::iterator it = doc.begin(); it != doc.end(); it++)
			{
				std::string str = *it;
				printf("%s\n", str.c_str());
			}
		}
	}
}


