#include <string>
#include <fstream>
#include <filesystem>
#include <cassert>
#include <print>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

class FileSensor
{
public:
    FileSensor(const std::filesystem::path& value_file) : _value_file{value_file} {}
    double get_value() const
    {
        int fd = open(_value_file.c_str(), O_RDONLY);
        if (fd == -1) {
            perror(std::format("open(\"{}\", O_RDONLY)", _value_file.string()).c_str());
            assert(false);
        }

        char tmp[64] = {0};
        ssize_t nread = read(fd, tmp, sizeof(tmp)-1/*room for C string termination*/);
        if (nread == -1) {
            perror("read");
            assert(false);
        }
        close(fd);

        return std::stod(tmp);
    }
private:
    std::filesystem::path _value_file;
};

class FileSwitch
{
public:
    FileSwitch(const std::filesystem::path& state_file)
    : _state_file(state_file) {}
    
    void set_state(bool state)
    {
        int fd = open(_state_file.c_str(), O_WRONLY|O_TRUNC);
        if (fd == -1) {
            perror(std::format("open(\"{}\", O_WRONLY|O_TRUNC)", _state_file.string()).c_str());
            assert(false);
        }

        static const char on = '1';
        static const char off = '0';

        ssize_t nwritten = write(fd, state?&on:&off, 1);
        if (nwritten == -1) {
            perror("write");
            assert(false);
        }
    }

    bool get_state()
    {
        int fd = open(_state_file.c_str(), O_RDONLY);
        if (fd == -1) {
            perror(std::format("open(\"{}\", O_RDONLY)", _state_file.string()).c_str());
            assert(false);
        }

        char c;
        ssize_t nread = read(fd, &c, 1);
        if (nread == -1) {
            perror("read");
            assert(false);
        }

        close(fd);

        return (c == '1');
    }

    std::string path() const { return _state_file.string(); }

private:
    std::filesystem::path _state_file;
};

int main()
{
    std::println("hier noch brav sein");
    return 0;
}
