// ShitList.C  -*- C++ -*-
// Copyright (c) 1998 Etienne BERNARD
// Copyright (C) 2002 Clinton Ebadi

// 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.

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <fstream>

#include "ShitList.H"
#include "StringTokenizer.H"

ShitList::ShitList(String filename)
  : listFileName(filename)
{
#ifdef HAVE_STL_CLEAR
  l.clear();
#endif
  read();
}

ShitList::~ShitList()
{
  clear();
}

void
ShitList::read()
{
  std::ifstream file(listFileName);
  String temp;
  int line = 1;

  clear();

  if (!file) {
    std::cerr << "I cannot find the file " << listFileName << std::endl;
    return;
  }

  while (file >> temp, temp.length() != 0) {
    StringTokenizer st(temp);
    String mask = st.nextToken(':');
    String channelMask = st.nextToken(':');
    String level = st.nextToken(':');
    String expiration = st.nextToken(':');
    String reason = st.rest().trim();
    l.push_back (new ShitEntry(mask, channelMask, std::atoi(level), 
			      std::atol(expiration), reason));
    line++;
  }
  file.close();
}

void
ShitList::save()
{
  std::list<ShitEntry *>::iterator it = l.begin();
  std::ofstream file(listFileName);

  if (!file)
    return;

  for ( ; it != l.end(); ++it)
    if ((*it)->isStillValid()) {
      file << (*it)->shitMask.getMask() << ":"
           << (*it)->shitChannelMask.getMask() << ":"
           << (*it)->shitLevel << ":"
           << (*it)->expirationDate << ":"
           << (*it)->shitReason << std::endl;
    }
}

void
ShitList::clear()
{
  ShitEntry *se;

  while (!l.empty()) {
    se = (*l.begin());
    l.erase(l.begin());
    delete se;
  }
}

void
ShitList::addShit(String m, String mc, int lev, time_t e, String r)
{
  l.push_back (new ShitEntry(m, mc, lev, e, r));
}


void
ShitList::delShit(String mask, String channelMask)
{
  for (std::list<ShitEntry *>::iterator it = l.begin();
       it != l.end();
       ++it)
    if ((*it)->shitMask.getMask() == mask &&
        (*it)->shitChannelMask.getMask() == channelMask) {
      delete (*it);
      l.erase(it);
      return;
    }
}

ShitEntry *
ShitList::getShit(String nuh, String channel)
{
  for (std::list<ShitEntry *>::iterator it = l.begin();
       it != l.end();
       ++it)
    if ((*it)->matches(nuh, channel)) {
      return (*it);
    }

  return 0;
}


syntax highlighted by Code2HTML, v. 0.9.1