/*
      _______                          .__ .__   .__   .__                 
      \      \    ____   __ __ _______ |__||  |  |  |  |__|  ____    ____  
      /   |   \ _/ __ \ |  |  \\_  __ \|  ||  |  |  |  |  | /  _ \  /    \ 
     /    |    \\  ___/ |  |  / |  | \/|  ||  |__|  |__|  |(  <_> )|   |  \
     \____|__  / \___  >|____/  |__|   |__||____/|____/|__| \____/ |___|  /
    =========\/======\/=================================================\/==
  v0.01 04/JUL/2007 © Copyright 2007-2007 Scott D. Yelich SOME RIGHTS RESERVED
 .,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.-*~'`^`'~*-,._.,-*~'`^`'~*-,. 


  LICENSE:  Creative Commons Attribution 3.0 License.
  SEE:      http://creativecommons.org/licenses/by/3.0/


  Sun Jul 29 21:33:38 EDT 2007, v0.02 sdy

  This is a *very* simple program written to do a web page
  hit counter using sqlite3.

*/

//  LOCAL

#include "Counter.h"

Counter::Counter()
{
  _sql3.open("/www/neurillion/p/33/databases/hits.sq3");
}

Counter::~Counter()
{
}

int
Counter::hit(std::string const & page)
{
  int rc;
  int hits=1;
  int ctime=0;
  time_t time_now = time(NULL);
  std::stringstream sql_command_ss;
  sql_command_ss.str("");
  sql_command_ss << "SELECT hits,time FROM counter_gd_totals WHERE page='" << page << "';";
  rc = _sql3.exec(sql_command_ss.str()); // order by?
  int header_size = _sql3.headers().size();
  //  if it doesn't exist, create it ...
  if (0 == header_size) {
    rc = _sql3.exec("CREATE TABLE counter_gd_totals (page,hits,time);");
    sql_command_ss << "INSERT INTO counter_gd_totals VALUES('";
    sql_command_ss << page << "'," << hits << "," << time_now << ");";
    rc = _sql3.exec(sql_command_ss.str());
  } else {
    sql_command_ss.str("");
    sql_command_ss << "UPDATE counter_gd_totals SET hits=hits+1,";
    sql_command_ss << "time=" << time_now;
    sql_command_ss << " WHERE page='" << page << "';";
    rc = _sql3.exec(sql_command_ss.str());
  }
  hits = Counter::hits(page);
  return hits;
}

int
Counter::hits(std::string const & page)
{
  int rc;
  int hits=0;
  std::stringstream sql_command_ss;
  sql_command_ss.str("");
  sql_command_ss << "SELECT hits FROM counter_gd_totals WHERE page='" << page << "';";
  rc = _sql3.exec(sql_command_ss.str()); // order by?
  int header_size = _sql3.headers().size();
  if (0 != header_size) {
    std::istringstream buffer(_sql3.data()[0]);
    if (!(buffer >> hits)); // throw?
  }
  return hits;
}

