import "../";
// inherit "roxenlib";

string formfile = combine_path( dirname(__FILE__), "form.html" );

object fotw;

string formpage(object id)
{
  if(!fotw && !(fotw = FOTW.Fotw()))
    return "ERROR: connection to fotw database FAILED.";
  int iid;
  if(id->variables->id)
    iid = (int)(id->variables->id);
  else
    {
      array stuff = fotw->query("select max(id) from fotw_main");
      if(!sizeof(stuff))
	error("ERROR: fotw_main table empty?\n");
      iid = (int)stuff[0]["max(id)"];
    }

  string qs = "select * from fotw_main where id=" + (string)iid;
  array stuff = fotw->query(qs);
  if(!sizeof(stuff))
    error("ERROR: invalid item id\n");
  string lang = stuff[0]->lang;
  string url = stuff[0]->url;
  string title_en = stuff[0]->title_en;
  string title_pl = stuff[0]->title_pl;
  string desc_en = sprintf("%-=80s", stuff[0]->desc_en);
  string desc_pl = sprintf("%-=80s", stuff[0]->desc_pl);
  return replace(Stdio.read_file(formfile),
		 ({"%NUM;","%CTIME;", "%LANG;", "%URL;", "%TITLE_EN;", "%TITLE_PL;", "%DESC_EN;", "%DESC_PL;", "%ID;"}),
		 ({(string)sizeof(fotw), ctime(time()), lang, url, title_en, title_pl, desc_en, desc_pl, (string)iid}));
}

string post_action(object id)
{
  string out = "<h1>Variables submitted from form:</h1><p>";
  foreach(indices(id->variables), string var)
    {
      out += sprintf("%s : %s<br />", var, _Roxen.html_encode_string(id->variables[var]));
    }
  //  return out;
  if(!fotw && !(fotw = FOTW.Fotw()))
    return out += "<strong>ERROR: connection to fotw database FAILED.</strong>";
  string qs = replace("update fotw_main set lang=':lang', url=':url', title_en=':title_en', title_pl=':title_pl', "
		      "desc_en=':desc_en', desc_pl=':desc_pl' where id=:id",
		      Array.map(indices(id->variables), lambda(string _){ return ":"+_;}), Array.map(values(id->variables), fotw->db->quote));
  fotw->query(qs);
  out += "<p><strong>Item with id = " + id->variables->id + " updated in fotw.</strong>" + 
    "<p><a href=\"/~rjb/fotw/\">return to fotw</a>";
  return out;
}

string parse(object id)
{
  switch(id->method)
    {
    case "GET":
      return formpage(id);
    case "POST":
      return post_action(id);
    default:
      return "ERROR: Unsupported method\n";
    }
}
