#ifndef INCLUDED_ROTATABLESTREAMBUF_
#define INCLUDED_ROTATABLESTREAMBUF_

#include <streambuf>
#include <fstream>
#include <iosfwd>
#include <thread>
#include <bobcat/semaphore>

class RotatingStreambuf: public std::streambuf
{
    std::mutex d_mutex;
    bool d_locked = false;
    volatile bool d_content = false;

    std::ofstream d_out;
    std::string d_name;

    int (RotatingStreambuf::*d_overflow)(int ch);
    void (*d_header)(std::ostream &);

    struct RotationInfo
    {
        RotatingStreambuf *rotationStreambuf;
        size_t lastRotation = 0;
        std::mutex rotationMutex;
    };

    static RotationInfo s_stdRotate;
    static RotationInfo s_dataRotate;

    static FBB::Semaphore s_semaphore;
    static std::thread s_rotateThread;
  
    public:
        RotatingStreambuf(void (*header)(std::ostream &) = 0);
        ~RotatingStreambuf() override;

        void open(std::string const &name, bool stdLog);
        static void notify();

        static void startThread();

        static void logRotate();                                        // .h
        static void dataRotate();                                       // .h

    private:
        int unlockedOverflow(int ch);
        int lockedOverflow(int ch);

                                                // called by rotateSthread at
                                                // --log-rotate time intervals 
        static void rotate();                                           // 1

        void rotate(size_t nRotations);                                 // 2

                                                // rotates the 'info' log-file
        static void rotate(RotationInfo &info);                         // 3

        static void rotateThread();

        static bool rotationsRequested();                               // .ih

        int overflow(int ch)    override;
        int sync()              override;
};

inline RotatingStreambuf::RotatingStreambuf(void (*header)(std::ostream &))
:
    d_header(header)
{}

// static
inline void RotatingStreambuf::logRotate()      // rotate the std. log file
{
    rotate(s_stdRotate);
}

// static
inline void RotatingStreambuf::dataRotate()     // rotate the data log file
{
    rotate(s_dataRotate);
}

#endif







