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

 Copyright 2014 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 *************************************/

#pragma once

#include <iostream>


class Counted
{
public:
    Counted() = default;
    virtual ~Counted();  // Change to virtual if base class
    Counted(const Counted&) = delete;
    Counted& operator=(const Counted&) = delete;
    void attach();
    void detach();
    int count() { return count_; }

protected:
    virtual void print(std::ostream&) const;  // Change to virtual if base class

private:
    int count_{0};

    friend std::ostream& operator<<(std::ostream& s, const Counted& p)
    {
        p.print(s);
        return s;
    }
    friend class CountedGC;
};

inline void destroy(Counted**) {}

template <class T>
class Handle
{
    T* ptr_{nullptr};

public:
    Handle(T* ptr = nullptr) :
        ptr_(ptr)
    {
        if (ptr_)
            ptr_->attach();
    }

    virtual ~Handle()
    {
        if (ptr_)
            ptr_->detach();
    }

    Handle(const Handle<T>& other) :
        ptr_(other.ptr_)
    {
        if (ptr_)
            ptr_->attach();
    }

    Handle<T>& operator=(const Handle<T>& other)
    {
        if (this != &other && ptr_ != other.ptr_) {
            if (ptr_)
                ptr_->detach();
            ptr_ = other.ptr_;
            if (ptr_)
                ptr_->attach();
        }
        return *this;
    }

    T* operator->() const { return ptr_; }
    T& operator*() const { return *ptr_; }

    operator T*() const { return ptr_; }

    bool operator<(const Handle<T>& other) const
    {
        return ptr_ < other.ptr_;
    }
};
