#ifndef ____script_h__
#define ____script_h__

#include "HTTPPage.h"

namespace http {

   class __script : public HTTPPage {
   
      int processCommand(std::string request, core::TCPSession *session, HTTPSession *httpSession, HTTPRequest *httpRequest, std::stringstream &data) override {
                  
         data << "function serverSend(url, type, receiver, formData, callback) {" << std::endl;
         data << "   var server = new XMLHttpRequest();" << std::endl;
         data << "   server.onload = function() {" << std::endl;
         data << "      if(server.readyState == 4 && server.status == 200)" << std::endl;
         data << "         callback(server.responseText, receiver);" << std::endl;
         data << "   };" << std::endl;
         data << "   server.open(type, url, true);" << std::endl;
         data << "   server.send(formData);" << std::endl;
         data << "}" << std::endl;

         data << "function getPage(url, receiver) {" << std::endl;
         data << "   serverSend(url, \"GET\", receiver, null, function(data, receiver) {" << std::endl;
         data << "      insertAndExecute(receiver, data);" << std::endl;
         data << "   });" << std::endl;
         data << "}" << std::endl;

         data << "function process(url, formName, receiver) {" << std::endl;
         data << "   var formElement = document.querySelector(\"form[name='\" + formName + \"']\");" << std::endl;
         data << "   var formData = new FormData(formElement);" << std::endl;
         data << "   serverSend(url, \"POST\", receiver, formData, function(data, receiver) {" << std::endl;
         data << "      insertAndExecute(receiver, data);" << std::endl;
         data << "   });" << std::endl;
         data << "}" << std::endl;
         
         data << "function insertAndExecute(id, text) {" << std::endl;
         data << "   idresolved = document.getElementById(id);" << std::endl;
         data << "   idresolved.innerHTML = text;" << std::endl;
	 data << "   var scriptarr = idresolved.getElementsByTagName(\"script\");" << std::endl;
	 data << "   if(scriptarr.length > 0) {" << std::endl;
	 data << "      var script = document.createElement(\"script\");" << std::endl;
	 data << "      script.type = \"text/javascript\";" << std::endl;
	 data << "      script.src = scriptarr[0].src;" << std::endl;
         data << "      document.getElementsByTagName(\"head\")[0].appendChild(script);" << std::endl;
	 data << "   }" << std::endl;
         data << "}" << std::endl;
            
         httpRequest->response.addHeader("Content-Type", "text/javascript"); 
  
         return true;
      }        
   };
}

#endif
