
#include <vdr/interface.h>
#include "NumberList.h"
#include "Settings.h"


cNumberList::cNumberList(string ListFile)
{
  m_ListFile = ListFile;
}


cNumberList::~cNumberList(void)
{
}


void cNumberList::saveList(void)
{
  Settings settings;

  settings.setValue( "count", size() );

  iterator curr = begin();
  unsigned int iPos = 0;
  while (curr != end())
  {
    settings.setValue( "pos_" + (string)itoa(iPos) + "_UIN",   (*curr)->getUIN() );
    settings.setValue( "pos_" + (string)itoa(iPos) + "_Alias", (*curr)->getUIN() );
    ++curr;
    iPos++;
  }
  
  try 
  {
    settings.save(m_ListFile);
  } catch(runtime_error& e) 
  {
    esyslog("vdricq: Can't save list %s '%s'", m_ListFile.c_str(), e.what());
  }
}

bool cNumberList::loadList(void)
{
  Settings settings;

  clear();

  try 
  {
    settings.load(m_ListFile);
  } catch(runtime_error& e) 
  {
    esyslog("vdricq: Can't load list %s '%s'", m_ListFile.c_str(), e.what());
    return false;
  }
  
  int count = settings.getValueInt("count");

  for (int iPos = 0; iPos < count; iPos++)
  {
    unsigned int iUIN = settings.getValueUnsignedInt("pos_" + (string)itoa(iPos) + "_UIN");
    string     sAlias = settings.getValueString     ("pos_" + (string)itoa(iPos) + "_Alias");
    if (iUIN != 0)
    {
      ICQ2000::ContactRef c = ICQ2000::ContactRef( new ICQ2000::Contact(iUIN) );
      c->setAlias(sAlias);
      insert(end(), c);
    }
  }
  return true;
}

bool cNumberList::inList(unsigned int iUIN)
{
  iterator curr = begin();
  while (curr != end())
  {
    if ((*curr)->getUIN() == iUIN)
      return true;

    ++curr;
  }

  return false;
}

void cNumberList::removeContact(unsigned int iUIN)
{
  iterator curr = begin();
  while (curr != end())
  {
    if ((*curr)->getUIN() == iUIN)
    {
      erase(curr);
      return;
    }

    ++curr;
  }
}


cNumberList::iterator cNumberList::find(unsigned int iUIN)
{
  iterator curr = begin();
  while (curr != end())
  {
    if ((*curr)->getUIN() == iUIN)
      return curr;

    ++curr;
  }

  return end();
}


ICQ2000::ContactRef cNumberList::getContact(unsigned int iUIN)
{
  return *find(iUIN);
}
