#include <stdarg.h>
#include <reg.h>
#include <debug.h>
#include <platform/debug.h>
#include <lib/printf.h>
#include <arch/ops.h>
#include <platform/osk5912/omap5912.h>

static void write_uart_reg(int uart, int reg, unsigned char data)
{
	unsigned long base;
	int mul = 4;

	switch(uart) {
		case 0: base = UART0_BASE; break;
		case 1: base = UART1_BASE; break;
		case 2: base = UART2_BASE; break;
		default: return;
	}

	*(volatile unsigned char *)(base + reg * mul) = data;
}

static unsigned char read_uart_reg(int uart, int reg)
{
	unsigned long base;
	int mul = 4;

	switch(uart) {
		case 0: base = UART0_BASE; break;
		case 1: base = UART1_BASE; break;
		case 2: base = UART2_BASE; break;
		default: return 0;
	}

	return *(volatile unsigned char *)(base + reg * mul);
}

static int uart_init(void)
{
	/* clear the tx & rx fifo and disable */
	write_uart_reg(0, UART_FCR, 0x6);

	return 0;
}

static int uart_putc(int port, char c )
{
	while (!(read_uart_reg(port, UART_LSR) & (1<<6))) // wait for the shift register to empty
		;
  	write_uart_reg(port, UART_THR, c);
	return 0;
}

static int uart_getc(int port, bool wait)  /* returns -1 if no data available */
{
	if (wait) {
		while (!(read_uart_reg(port, UART_LSR) & (1<<0))) // wait for data to show up in the rx fifo
			;
	} else {
		if (!(read_uart_reg(port, UART_LSR) & (1<<0)))
			return -1;
	}
	return read_uart_reg(port, UART_RHR);
}

int dputs(const char *str)
{
	int state = arch_disable_ints();

	while(*str != 0) {
		if(*str == '\n')
			uart_putc(0, '\r');
		uart_putc(0, *str++);
	}

	arch_restore_ints(state);

	return 0;
}

int dprintf(const char *fmt, ...)
{
	char buf[256];
	int err;

	va_list ap;
	va_start(ap, fmt);
	err = vsprintf(buf, fmt, ap);
	va_end(ap);

	dputs(buf);

	return err;
}

int dvprintf(const char *fmt, va_list ap)
{
	char buf[256];
	int err;

	err = vsprintf(buf, fmt, ap);

	dputs(buf);

	return err;
}

void debug_dump_regs(void)
{
	PANIC_UNIMPLEMENTED;
}

void debug_halt(void)
{
	dprintf("HALT: spinning forever...\n");
	for(;;);
}

void debug_dump_memory_bytes(void *mem, int len)
{
	PANIC_UNIMPLEMENTED;
}

void debug_dump_memory_halfwords(void *mem, int len)
{
	PANIC_UNIMPLEMENTED;
}

void debug_dump_memory_words(void *mem, int len)
{
	PANIC_UNIMPLEMENTED;
}

void debug_set_trace_level(int trace_type, int level)
{
	PANIC_UNIMPLEMENTED;
}

uint32_t debug_cycle_count()
{
	PANIC_UNIMPLEMENTED;
}
