#include <FL/Fl.h>
#include <FL/fl_ask.h> 
#include <sptk3/CHttpConnect.h>
#include <sptk3/CGroup.h>
#include <sptk3/CWindow.h>
#include <sptk3/CProgressBar.h>
#include <sptk3/CInput.h>
#include <sptk3/CButton.h>
#include <sptk3/CEditor.h>
#include <sptk3/CDataControl.h>

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

// Buffer size for read buffer
// The smaller it is, more responsible interface will be.
// Though, you may loose in speed lil bit.
//#define BUFFER_SIZE 16384
//#define BUFFER_SIZE 4096
#define BUFFER_SIZE 1024

CHttpConnect   *sock;
CInput         *input;
CEditor        *textdisp;

CProgressBar   *p_bar;
CBox        *p_text;

void go_callback(Fl_Widget *,void *) 
{    
   p_bar->minimum(0);
   p_bar->maximum(1);
   p_bar->data(0);
   p_text->label("...");

   textdisp->textBuffer()->text("");    
   textdisp->redraw();

   std::string  pageName = input->data();
   int pos = pageName.find("/");
   if (pos < 1) {
      fl_alert("Please, use the correct host name");
      return;
   }
   string hostName = pageName.substr(0,pos);
   pageName.erase(pageName.begin(),pageName.begin()+pos+1);

   pos = pageName.find("/");
   if (pos < 0) 
      pageName += "/index.html";

   CHttpParams httpFields;

   httpFields["first_name"] = "alex";
   httpFields["last_name"] = "parshin";

   try {
      sock->host(hostName);
      sock->open();
      sock->cmd_get(pageName,httpFields);
      sock->close();
      textdisp->textBuffer()->text(sock->htmlData().data());
   }
   catch(CException &e) {
      puts(e.what());
      return;
   }
}

int main(int argc,char *argv[]) 
{
   CHttpConnect socket;
   sock = &socket;

   CWindow main_window(600,400,"CHttpConnect test");

   CGroup top_group("",25);
   top_group.layoutSpacing(1);

   CBox progress_text("",150,SP_ALIGN_LEFT);
   p_text = &progress_text;

   CProgressBar progress_bar("",100,SP_ALIGN_LEFT);
   progress_bar.box(FL_THIN_DOWN_BOX);
   p_bar = &progress_bar;

   top_group.end();

   CEditor  editor(10,SP_ALIGN_CLIENT);

   textdisp = &editor;

   CGroup status_line("",25,SP_ALIGN_BOTTOM);
   status_line.layoutSpacing(1);

   CInput url_input("http://",300,SP_ALIGN_LEFT);
   url_input.data("www.tts-sf.com/index.html");

   CButton go_button(SP_EXEC_BUTTON,SP_ALIGN_LEFT,"Go");
   go_button.callback(go_callback);

   status_line.end();

   input = &url_input;

   main_window.end();
   main_window.resizable(main_window);
   main_window.show(argc,argv);

   return Fl::run();
}
