/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "Counted.h"
#include "Runnable.h"

#include <set>

class CountedGC : public Runnable
{
public:
    void push(Counted*);

private:
    std::set<Counted*> dead_;
    virtual void run();
};

void CountedGC::push(Counted* c)
{
    dead_.insert(c);
    enable();
}

void CountedGC::run()
{
    if (dead_.size() == 0) {
        disable();
        return;
    }

    Counted* c = *dead_.begin();
    dead_.erase(c);

    if (c->count_ != 0)
        cout << "CountedGC " << *c << " has a non-zero count "
             << c->count_ << endl;
    else {
        //	cout << "CountedGC delete " << *c << endl;
        delete c;
    }
}


Counted::Counted() :
    count_(0)
{
}

Counted::~Counted()
{
}

void Counted::attach()
{
    count_++;
}

void Counted::detach()
{
    if (--count_ == 0) {
        static CountedGC* gc = new CountedGC();
        gc->push(this);
    }
}

void Counted::print(ostream&) const
{
}