#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "String.h"
#include "Action.h"
#include "HttpServ.h"

Action * Action::start = 0;

static int counter = 0;

static String genurl(const String & u) {
    if (u.strlen()) {
	return u;
    } else {
	// Si l'url pass�e en param�tre est vide, on g�n�re une URL
	// sous la forme TmpXXXX o� XXXX est une valeur qui s'incr�mente.
	return String("Tmp") + (counter++);
    }
}

Action::Action(const String & u) : next(start), prev(0), URL(genurl(u)), hastoclean(false), accessed(false) {
    start = this;
    if (next) next->prev = this;
}

Action::~Action() {
    if (start == this) {
	start = next;
    }
    if (next) next->prev = prev;
    if (prev) prev->next = next;
}

Action * Action::Look4URL(const String & URL) {
    Action * p;
    
//    cerr << "Looking for " << URL << endl;
    for (p = start; p; p = p->next) {
//	cerr << "p->GetURL() = " << p->GetURL() << endl;
	if (!p->GetURL().strlen()) {
	    // Si l'action que l'on vient de tester n'a pas d'URL, elle ne sert � rien.
	    // On l'efface donc de notre liste. GetURL renvoie une chaine vide si l'action
	    // �tait d�clar�e en mode CleanUp, puis a �t� acc�d�e.
	    delete p;
	} else {
	    if (URL == p->GetURL()) return p;
	}
    }
    
    return 0;
}

/*
 * Voici la skin principale. Elle n�cessite un fichier 'grain.png' dans le r�pertoire datas
 * et un fichier 'style.css' (fournis)
 */

void Action::SendHead(Handle * h) {
    (*h) << "<HTML><HEAD><TITLE>" << GetTitle() << "</TITLE>" << endnl <<
    "<META http-equiv=\"Content-Style-Type\" content=\"text/css\">" << endnl <<
    "<LINK REL=STYLESHEET HREF=\"/image/style.css\" TYPE=\"text/css\">" << endnl <<
    "</HEAD><BODY BGCOLOR=\"#aaaaaa\" BACKGROUND=\"/image/grain.png\">" << endnl <<
    "<center><TABLE WIDTH=\"50%\" BORDER=3 cellspacing=1 BGCOLOR=\"#ffffff\"><TR><TD>" << endnl <<
    "<center><b><h1>" << GetTitle() << "</h1></b></center></TD></TR></TABLE><P>" << endnl <<
    "<TABLE WIDTH=\"80%\" BORDER=2 cellspacing=1 BGCOLOR=\"#ffffff\"><TR><TD>" << endnl;
}

void Action::SendFoot(Handle * h) {
    (*h) << "</TABLE></TD></TR></BODY></HTML>" << endnl;
}

String Action::GetURL(void) {
    // Comme d�crit plus haut, il faut renvoyer la cha�ne vide si l'action est en
    // mode CleanUp et a �t� lue.
    return (hastoclean && accessed) ? "" : URL;
}

void Action::CleanUp(void) {
    hastoclean = true;
}

void Action::Accessed(void) {
    accessed = true;
}

void Action::ShowButton(Handle * h, const String & l, const String & u) {
    (*h) << "<CENTER><FORM METHOD=\"POST\" ACTION=\"/bin/" << u << "\">" << endnl <<
        "<INPUT TYPE=\"SUBMIT\" VALUE=\"" << l << "\">" << endnl
	<< "</FORM></CENTER>" << endnl;
}