#include "baseserv.h"

class TCoffeeServer : public TBaseServerApp
{
protected:  
	virtual const wxChar* GetAppName() const;
  virtual void ProcessCommand(wxString cmd, wxSocketBase& outs);

public:
	bool IsMagicName(wxString& strFilename) const;
  void GenerateFile(wxString& strFilename);
};

// Implementare almeno queste due funzioni pure virtuali

const wxChar* TCoffeeServer::GetAppName() const
{
	return "Coffee";
}

bool TCoffeeServer::IsMagicName(wxString& strFilename) const
{
  wxString strName;
	wxSplitPath(strFilename, NULL, &strName, NULL);
  strName.MakeLower();
  const int q = strName.Find('?');
	if (q > 0)
	  strName.Truncate(q);

	if (strName == "index")
	{
		strFilename = strName;
		return true;
	}
	if (strName == "log")
	{
		strFilename = GetLogFileName();
	}
  if (strName == "buy")
	{
		return true;
	}

  return false;
}

void TCoffeeServer::GenerateFile(wxString& strFilename)
{
  wxString strName, strArgs;
	wxSplitPath(strFilename, NULL, &strName, NULL);
  strName.MakeLower();
  const int q = strFilename.Find('?');
	if (q > 0)
		strArgs = strFilename.Mid(q+1);

	const char* items[] = { "Coffee", "Cappuccino", "Chocolate", "Milk", "Tea", "Brioche", NULL };

	if (strName == "index")
	{
		TXmlItem html; 
		TXmlItem& body = CreatePageBody(html).AddChild("center");

		body.AddChild("h1") << "Welcome to the virtual coffee machine";
		body.AddChild("br");

		TXmlItem& table = body.AddChild("table");
    table.SetAttr("width", "50%").SetAttr("border", "1");

		for (int i = 0; items[i]; i++)
		{
      TXmlItem& row = table.AddChild("tr");
			TXmlItem& a = row.AddChild("td").AddChild("a");
			a.SetAttr("href", wxString::Format("buy.cgi?%d", i));
			a.AddChild("img").SetAttr("src", "rbutton.gif").SetAttr("border", "0");
      row.AddChild("td") << items[i];
		}

		strFilename = GetTempFilename();
		html.Save(strFilename);
	}

	if (strName == "buy")
	{
		TXmlItem html; 
		TXmlItem& body = CreatePageBody(html).AddChild("center");

		const int nItem = atoi(strArgs);
		const wxString strItemCode = wxString::Format("Item%d", nItem);
    const int nSold = GetConfigInt(strItemCode)+1;
		SetConfigInt(strItemCode, nSold);

		body.AddChild("h1") << wxString::Format("%d %ss sold.", nSold, items[nItem]);
		body.AddChild("br");
		body.AddChild("h2") << "You'll be billed 1 Euro on your next wage :-)";

		AddLinkButton(body, "Return to main page", "index.htm");
		strFilename = GetTempFilename();
		html.Save(strFilename);
	}

	if (strName == "log")
	{
		strFilename = GetLogFileName();
	}
}

void TCoffeeServer::ProcessCommand(wxString cmd, wxSocketBase& outs)
{
	if (cmd.StartsWith("GET "))
	{
		const int stop = cmd.Find(" HTTP");
		wxString str = cmd.Mid(4, stop-4).Trim();
		if (str == "/")
			str += "index.htm";
		wxString strFilename = GetDocumentRoot() + str;

		if (IsMagicName(strFilename))
			GenerateFile(strFilename);

		SendFile(strFilename, outs);
	}
}

// Istanziare l'applicazione principale

IMPLEMENT_APP(TCoffeeServer)