#include "can-jf0815-hw.h"
#include <why-irq.h>
#include <why-time.h>
#include <why-timer.h>
#include <why-spinlock.h>
#include <why-mutex.h>
#include <why-thread.h>
#include <why-semaphore.h>
#include <why-messagequeue.h>
#include <print>
#include <vector>


class Broadcaster
{
public:
    using Notifier = std::function<void(int/*wert*/)>;

public:
    void set(int value)
    {
        _notifiers_lock.lock();
        for (auto n: _notifiers)
            n(value);                                  // <-- calling out while holding a lock (WAAH)
        _notifiers_lock.unlock();
    }
    void register_notifier(Notifier n)
    {
        _notifiers_lock.lock();
        _notifiers.push_back(n);
        _notifiers_lock.unlock();
    }
private:
    Why::Mutex _notifiers_lock;
    std::vector<Notifier> _notifiers;
};

class Objekt
{
public:
    Objekt() : _mein_inhalt(std::format("inhalt ist noch nicht da {}", 0)) {}
    void start(Broadcaster& bc)
    {
        bc.register_notifier([this](int value){
            _mein_inhalt = std::format("jetzt hamma einen inhalt, naemlich {}", value);
        });
    }
    const std::string& inhalt() const { return _mein_inhalt; }
private:
    std::string _mein_inhalt;
};

class Service
{
public:
    Service(Broadcaster& bc)
    : _thread([this, &bc](){
        int i = 5;
        for (;;) {
            Why::sleep_milli(500);
            _inhalt_lock.lock();
            std::println("Service hat den inhalt: {}", _inhalt);
            _inhalt_lock.unlock();
            if (i-- == 0)
                bc.register_notifier([this, &bc](int value){
                    _inhalt_lock.lock();
                    _inhalt = std::format("jetzt ist das service richtig da, der wert ist {}", value);
                    _inhalt_lock.unlock();

                    bc.register_notifier([](int value){});    // <-- deadlock, or other bad things (WAAH)
                });
        }
    }) {}
private:
    Why::Thread _thread;
    Why::Mutex _inhalt_lock;
    std::string _inhalt = "noch nicht da";
};

int main()
{
    Why::init();
    
    Broadcaster bc;

    Service service(bc);

    Objekt objekt;
    objekt.start(bc);
    
    std::println("objekt vor dem ersten broadcast: {}", objekt.inhalt());

    bc.set(42);

    std::println("objekt nach dem ersten broadcast: {}", objekt.inhalt());

    Why::sleep_milli(5000);

    int value = 666;
    for (;;) {
        bc.set(value++);
    }

    Why::pause();

    return 0;
}
