// $Id: ErrorCodes.cpp 1301 2022-03-22 16:50:46Z ge $
/// \file ErrorCodes.cpp
/// \brief contains the ErrorCodes class static initialization
///
/// $Revision: 1301 $
/// \author Gerald Weber <gweberbh@gmail.com>
#define GBC_ERRORCODES_CPP "$Id: ErrorCodes.cpp 1301 2022-03-22 16:50:46Z ge $"

#include <iostream>
#include <boost/regex.hpp>
#include "ErrorCodes.h"

using namespace gbc;

using namespace std;

bool DebugControl::EmptyDebugMap=true;

bool DebugControl::DebugAll=false;

bool DebugControl::RegexCodes=false;

DebugControl::debug_map_type    DebugControl::DebugMap=debug_map_type();

void DebugControl::enable(std::string code)
  {
  EmptyDebugMap=false;
  
  if (code == "ALL") 
    {
    enable_all();
    return;
    }
  
  DebugMap[code]=true;
  COUT_INFO(INFOEDF) << " enabling debug flag \"" << code << "\"" << std::endl;
  
  const boost::regex pattern("^.*[^[:alnum:]_]+.*$"); //anything that is not alphanumeric nor contains _ is potentially a regex
  if (boost::regex_match(code,pattern)) 
    {
    RegexCodes = true;
    COUT_INFO(INFODFREG) << " debug flag \"" << code << "\" will be handled as regular expression " << std::endl;
    }
  
  }
  
void DebugControl::disable(std::string code)
  {
  if (code == "ALL") 
    {
    disable_all();
    return;
    }
    
  auto fnd = DebugMap.find(code);
  
  if (fnd != DebugMap.end())
    {
    DebugMap.erase(fnd);
    COUT_INFO(INFORDF) << " removing debug flag \"" << code << "\"" << std::endl;
    }
  else
    COUT_INFO(INFODFNF) << " debug flag \"" << code << "\" not found" << std::endl;
  
  }

    

  
void DebugControl::enable_all(void)
  {
  DebugAll=true;
  COUT_INFO(INFOAEDF) << " enabling all debug flags" << std::endl;
  }
  
void DebugControl::disable_all(void)
  {
  DebugAll=false;
  DebugMap.clear();
  COUT_INFO(INFODSDF) << " disabling all debug flags" << std::endl;
  }

bool DebugControl::debug(std::string code)
  {
  if (DebugAll) return true;
  if (EmptyDebugMap) return false;
  else 
    {
    if (DebugMap.find(code) != DebugMap.end()) return true;
    else
      {
      if (RegexCodes) 
        {
        for(auto regex_code : DebugMap)
          {
          const boost::regex pattern(regex_code.first); //consider that code may be a regex
          if (boost::regex_match(code,pattern)) return true;
          }
        }
      }
    }
  return false;
  }

