/* ====================================================================
 * Copyright (c) 2003-2008  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 <QtCore/QString>
#include <QtCore/QRegExp>

// sys
#include <algorithm>


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


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

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

static bool lessConfigValue( const ConfigValue& left, const ConfigValue& right )
{
  return left.getKey() < right.getKey();
}

void ConfigData::save()
{
  std::sort(_data.begin(),_data.end(), lessConfigValue );
  _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::delValue( const sc::String& key )
{
  delValues( key, _data, false );
}

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);
    }
  }
}
