/*
 *  Copyright (c) 2011 Cyrille Berger <cberger@cberger.net>
 *
 * This library 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, or (at your option) any later version of the License.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; see the file COPYING.RUNTIME.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * The file COPYING.RUNTIME.EXCEPTION contains an exception that allow
 * to use this file with other open source license
 */

#include "Reporter.h"

#include <cstdlib>
#include <iostream>
#include <list>

using namespace Cauchy::xUnit;

struct Reporter::Private
{
  class StaticDeleter;
  struct Message {
    Message(const std::string& _text, int _line) : text(_text), line(_line)
    {}
    std::string text;
    int line;
  };
  static Reporter* s_instance;
  static StaticDeleter s_instanceDeleter;
  std::list< Message > sucesses;
  std::list< Message > errors;
};

class Reporter::Private::StaticDeleter
{
public:
  ~StaticDeleter()
  {
    delete Reporter::Private::s_instance;
  }
};

Reporter* Reporter::Private::s_instance = 0;

Reporter::Private::StaticDeleter Reporter::Private::s_instanceDeleter;


Reporter::Reporter() : d(new Private)
{
}

Reporter::~Reporter()
{
  if(not d->errors.empty())
  {
    std::cerr << "Successful tests: " << std::endl;
    for(std::list<Private::Message>::iterator it = d->sucesses.begin();
        it != d->sucesses.end(); ++it)
    {
      std::cerr << "  " << it->line << ": " << it->text << std::endl;
    }
    std::cerr << std::endl << "Failed tests: " << std::endl;
    for(std::list<Private::Message>::iterator it = d->errors.begin();
        it != d->errors.end(); ++it)
    {
      std::cerr << "  " << it->line << ": " << it->text << std::endl;
    }
    std::abort();
  }
  delete d;
}

Reporter* Reporter::instance()
{
  if(Private::s_instance == 0)
  {
    Private::s_instance = new Reporter;
  }
  return Private::s_instance;
}

void Reporter::reportSuccess(const std::string& msg, int line)
{
  d->sucesses.push_back(Private::Message(msg, line));
}

void Reporter::reportFailure(const std::string& msg, int line)
{
  d->errors.push_back(Private::Message(msg, line));
}
