#include "device.h"
using namespace std;

bool Device::test() { return true; }

unsigned char Device::read() { return 0; }

void Device::write(unsigned char) {}

InputDevice::InputDevice(istream& in) {
    input = &in;
}

unsigned char InputDevice::read() {
    char c;
    if (input->get(c)) {
        return static_cast<unsigned char>(c);
    }
    return 0;
}

OutputDevice::OutputDevice(ostream& out) {
    output = &out;
}

void OutputDevice::write(unsigned char c) {
    output->put(static_cast<char>(c));
    output->flush();
}

FileDevice::FileDevice(string& filename) {
    file.open(filename, ios::in | ios::out | ios::binary);
    if (!file.is_open()) {
        // ustvari datoteko
        file.clear();
        file.open(filename, ios::out | ios::binary);
        file.close();
        file.open(filename, ios::in | ios::out | ios::binary);
    }
}

bool FileDevice::test() {
    return file.is_open();
}

unsigned char FileDevice::read() {
    char c;
    if (file.get(c)) {
        return static_cast<unsigned char>(c);
    }
    return 0;
}

void FileDevice::write(unsigned char c) {
    file.put(static_cast<char>(c));
    file.flush();
}
