// common/Configuration.cc
// This file is part of Decimail; see http://decimail.org
// (C) 2004 Philip Endecott
 
// This is version $Name$
//   (if there is no version (e.g. V0-1) mentioned in the previous line,
//    this is probably a snapshot from between "official" releases.)
 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#include "Configuration.hh"

#include "DmDatabase.hh"

#include "utils.hh"

#include <string>
using namespace std;


string Configuration::get_str(string variable)
{
  data_t::const_iterator i = data.find(variable);
  if (i==data.end()) {
    throw "No such configuration variable '"+variable+"'";
  };
  return i->second;
}

string Configuration::get_str(string variable, string def)
{
  data_t::const_iterator i = data.find(variable);
  if (i==data.end()) {
    return def;
  };
  return i->second;
}


int Configuration::get_num(string variable)
{
  string value = get_str(variable);
  return string_to_int(value);
}

int Configuration::get_num(string variable, int def)
{
  data_t::const_iterator i = data.find(variable);
  if (i==data.end()) {
    return def;
  };
  return string_to_int(i->second);
}

static bool string_to_bool(string s)
{
  ci_string si(s.c_str());
  return (si=="t" || si=="true" || si=="y" || si=="yes");
}

bool Configuration::get_bool(string variable)
{
  string value = get_str(variable);
  return string_to_bool(value);
}

bool Configuration::get_bool(string variable, bool def)
{
  data_t::const_iterator i = data.find(variable);
  if (i==data.end()) {
    return def;
  };
  return string_to_bool(i->second);
}



void Configuration::load(void)
{
  DmDatabase db;
  DmDatabase::Query q(&db);

  q << "select variable, type, value from configuration;";
  q.run();

  for(int i=0; i<q.get_ntuples(); ++i) {
    string variable = q.get(i,"variable");
    string value = q.get(i,"value");
    data.insert(make_pair(variable,value));
  }
}


/*static*/ Configuration& Configuration::singleton(void)
{
  static Configuration c;
  return c;
}
