/* ====================================================================
 * Copyright (c) 2003-2006, Martin Hauner
 *                          http://subcommander.tigris.org
 *
 * Subcommander is licensed as described in the file doc/COPYING, which
 * you should have received as part of this distribution.
 * ====================================================================
 */

// sc
#include "ConfigData.h"
#include "Config.h"

// qt
#include <qstring.h>
#include <qregexp.h>


static ConfigValue NullValue( sc::String(""), sc::String("") );


ConfigData::ConfigData( Config* cfg )
: _cfg(cfg)
{
}

void ConfigData::load()
{
  _cfg->get(_data);
}

void ConfigData::save()
{
  _cfg->set(_data);
}

void ConfigData::getValues( const sc::String& key, ConfigValues& values )
{
  getValues( key, _data, values, true );
}

void ConfigData::delValues( const sc::String& key )
{
  delValues( key, _data, true );
}

void ConfigData::setValues( const sc::String& key, const ConfigValues& values )
{
  delValues( key, _data, true );
  _data.insert( _data.end(), values.begin(), values.end() );
}

ConfigValue ConfigData::getValue( const sc::String& key )
{
  ConfigValues values;
  getValues(key,_data,values,false);

  if( values.size() != 1 )
  {
    return NullValue;
  }

  return values.front();
}

void  ConfigData::setValue( const sc::String& key, const ConfigValue& value )
{
  delValues( key, _data, false );
  _data.push_back(value);
}

void ConfigData::getValues( const sc::String& key, const ConfigValues& srcValues, ConfigValues& values, bool all )
{
  QString reStr = QString::fromUtf8(key).replace( ".", "\\." );
  if( all )
  {
    reStr += ".*";
  }
  QRegExp re(reStr);

  for( ConfigValues::const_iterator it = srcValues.begin(); it != srcValues.end(); it++ )
  {
    const ConfigValue& val = *it;

    if( re.exactMatch(QString::fromUtf8(val.getKey())) )
    {
      values.push_back(val);
    }
  }
}

void ConfigData::delValues( const sc::String& key, ConfigValues& values, bool all )
{
  ConfigValues tmp;
  values.swap(tmp);

  QString reStr = QString::fromUtf8(key).replace( ".", "\\." );
  if( all )
  {
    reStr += ".*";
  }
  QRegExp re(reStr);

  for( ConfigValues::const_iterator it = tmp.begin(); it != tmp.end(); it++ )
  {
    const ConfigValue& val = *it;

    if( ! re.exactMatch(QString::fromUtf8(val.getKey())) )
    {
      values.push_back(val);
    }
  }
}


syntax highlighted by Code2HTML, v. 0.9.1