#ifndef _COOKIE_AUTH_H
#define _COOKIE_AUTH_H

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

#include "cookie.h"
#include "csv.h"

#define PASSWORD_FILE "/home/mcoan/public_html/cgi-bin/passwd.csv"

namespace cgi_tools {

using namespace std;
using namespace csv_reader;

inline
bool cookie_auth(const string & user, 
                 const string & pass, 
                 const long timeout = 60 * 10)
{
   bool ret = false;
//cout << "Content-type: text/html\r\n\r\n" << flush;
   string user0, pass0;
   CookieListType * pCookieList = getCookieList();
   if(pCookieList) {
      for(CookieListType::iterator p = pCookieList->begin();
          p != pCookieList->end(); p++) {
         Cookie * & pCookieRef = (*p);
         if(pCookieRef->name() == string("MY_USER")) {
            user0 = pCookieRef->value();
            string::size_type ptr = user0.find(":");
            pass0 = user0.substr(ptr+1);
            user0 = user0.substr(0, ptr);
            break;
         }
/*
         else if(pCookieRef->name() == string("MY_PASS")) {
            pass0 = pCookieRef->value();
         }
*/
      }
   }

   if(user0 == "" || pass0 == "") {
      bool found = false;
      ifstream fin(PASSWORD_FILE, ios::in);
      if(fin) {
         csv_row_type row;
         while(fin >> row) {
            if(row.size() == 2) {
               if(row[0] == user && row[1] == pass) {
                  user0 = row[0];
                  pass0 = row[1]; 
                  found = true;
                  break; 
               }
            }
         }
         fin.close();
      }
      if(found) {
         Cookie c1(_strdup("MY_USER"),
                   _strdup((user+":"+pass).c_str()),
                   0, 0, false,
                   time(NULL) + timeout);
         c1.setCookie();
/*
         Cookie c2(_strdup("MY_PASS"),
                   _strdup(pass.c_str()),
                   0, 0, false,
                   time(NULL) + timeout);
         c2.setCookie();
*/
      }
   }
//cout << "user=" << user << "<BR>" << endl;
//cout << "pass=" << pass << "<BR>" << endl;
//cout << "user0=" << user0 << "<BR>" << endl;
//cout << "pass0=" << pass0 << "<BR>" << endl;
   if(user != "" && pass != "") {
      if(user == user0 && pass == pass0) {
          ret = true;
      }
   }
   
   if(pCookieList) {
      deleteCookieList(pCookieList);
   }

   return ret;
}

}


#endif /* _COOKIE_AUTH_H */
