/***************************** 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_;
    void run() override;
};

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)
        std::cout << "CountedGC " << *c << " has a non-zero count "
                  << c->count_ << std::endl;
    else {
        //	cout << "CountedGC delete " << *c << std::endl;
        delete c;
    }
}

Counted::~Counted() = default;

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

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

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