#pragma once
#include <myapp/persistence/database.h>
#include <myapp/persistence/databasefactory.h>
#include <myapp/logging/logger.h>
#include <myapp/logging/loggerfactory.h>
#include <memory>
#include <string>

using namespace myapp;

class readouts
{
private:
    std::shared_ptr<logging::logger> logger_;
    std::shared_ptr<persistence::database> db_;
    std::string device_;

    readouts()
    {
    }

public:
    void initialize(std::string connection_string)
    {
        logger_ = logging::logger_factory::create_console_logger();
        db_ = persistence::database_factory::create_redis(connection_string, logger_);
    }

    std::string get_last_value(std::string const& topic)
    {
        using namespace std::string_literals;

        try 
        {
            return db_->last_readout(topic);
        }
        catch (std::runtime_error const& e)
        {
            logger_->warning("READOUT", "Error while reading '"s + topic + "': "s + e.what());
            return std::string{};
        }

        logger_->warning("READOUT", "Handler not registered for '"s + topic + "'"s);
        return std::string{};
    }

    static std::shared_ptr<readouts> instance()
    {
        static std::weak_ptr<readouts> ref;
        std::shared_ptr<readouts> instance_;

        if (!ref.expired())
        {
            instance_ = ref.lock();
        }
        else
        {
            instance_ = std::shared_ptr<readouts>(new readouts());
            ref = instance_;
        }

        return instance_;
    }
};
