#include "switch.h"

#include <cassert>
#include <fcntl.h>
#include <unistd.h>


static bool read_state(const std::filesystem::path& control_file)
{
    int fd = open(control_file.c_str(), O_RDONLY);
    if (fd == -1) {
        perror(std::format("open(\"{}\", O_RDONLY)", control_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');
}

static void write_state(const std::filesystem::path& control_file, bool state)
{
    int fd = open(control_file.c_str(), O_WRONLY|O_TRUNC);
    if (fd == -1) {
        perror(std::format("open(\"{}\", O_WRONLY|O_TRUNC)", control_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);
    }
}

Switch::Switch(const std::filesystem::path& control_file)
: _control_file(control_file)
{
    write_state(_control_file, false);  // Initialize to OFF
}

void Switch::set_state(bool state)
{
    if (state != get_state())
        write_state(_control_file, state);
}

bool Switch::get_state() const
{
    return read_state(_control_file);
}
