#include <drivers/serial/serial.h>
#include <common.h>

#define COM1 0x3F8

int is_transmit_empty() {
    return inb(COM1 + 5) & 0x20;
}

void write_serial(char a) {
    while (is_transmit_empty() == 0);
    outb(COM1, a);
}

void print_serial(const char* str) {
    for (int i = 0; str[i] != '\0'; i++) {
        write_serial(str[i]);
    }
}

void print_serial_hex(uint32_t val) {
    char hex_chars[] = "0123456789ABCDEF";
    print_serial("0x");
    for (int i = 28; i >= 0; i -= 4) {
        write_serial(hex_chars[(val >> i) & 0x0F]);
    }
}

void init_serial() {
  outb(COM1 + 1, 0x00);    // Disable all interrupts
  outb(COM1 + 3, 0x80);    // Enable DLAB (set baud rate divisor)
  outb(COM1 + 0, 0x01);    // Set divisor to 1 (lo byte) -> 115200 baud
  outb(COM1 + 1, 0x00);    //                  (hi byte)
  outb(COM1 + 3, 0x03);    // 8 bits, no parity, one stop bit
  outb(COM1 + 2, 0xC7);    // Enable FIFO, clear them, with 14-byte threshold
  outb(COM1 + 4, 0x0B);    // IRQs enabled, RTS/DSR set
}
