#include "__cookie.h"
#include "Exception.h"
#include "Operand.h"
#include <iostream>
#include <ctime>

namespace jet {
   
   __cookie::__cookie(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
      output = false;
      if(!global.cgi)
	throw coreutils::Exception("must enable cgi mode on jet tag to use cookie tag.");
      if(!keywordDefined("name"))
	throw coreutils::Exception("header tag must have name defined.");
      if(!keywordDefined("expr") && keywordDefined("value") && hasContainer)
	throw coreutils::Exception("header tag cannot have both value and a container.");
      if(keywordDefined("expr") && !keywordDefined("value") && hasContainer)
	throw coreutils::Exception("header tag cannot have both expr and a container.");
      if(keywordDefined("expr") && keywordDefined("value") && !hasContainer)
	throw coreutils::Exception("header tag cannot have both expr and value.");
      if(!keywordDefined("expr") && !keywordDefined("value") && !hasContainer)
	throw coreutils::Exception("header tag must have a value, expr or a container.");
      if(keywordDefined("expr")) {
	 if(keywordDefined("eval"))
	   throw coreutils::Exception("Cannot use eval with expr.");	 
	 global.headers[keywords[resolveKeyword("name")]] = Operand(keywords["expr"], *this).string;	    
      } else if(hasContainer) {
	 processContainer(container);
	 if(evaluate) {
	    global.headers[keywords[resolveKeyword("name")]] = out;	       
	 } else {	   
	    global.headers[keywords[resolveKeyword("name")]] = container;
	 }	    
      } else {
	 global.headers[keywords["Set-Cookie"]] = keywords[resolveKeyword("value")];
      }      
   }      
}


/*              write(so, "Set-cookie: ", 12);
               write(so, cookie->name, cookie->lname);
               write(so, "=", 1);
               write(so, cookie->value, cookie->lvalue);

               // If cookie has expiration then calculate the unix time for the time value.

               if(cookie->ltimeout > 0) 
{

                     timeout_value = atoi(null_terminated(cookie->timeout, cookie->ltimeout));
                     if(timeout_value > 0) 
     {

	                     time(&time_value);
	                     time_value += timeout_value;
	                     timeout_struct = localtime(&time_value);
	                     time_length = strftime(cookie_timeout_buffer, sizeof(cookie_timeout_buffer), "%a, %d-%b-%Y %H:%M:%S %Z", timeout_struct);            $
	                       write(so, "; Expires=", 10);
	                     write(so, cookie_timeout_buffer, time_length);
     }

}


               write (so, "\n", 1);  */

