#include <debug.h>
#include <list.h>
#include <malloc.h>
#include <string.h>
#include <err.h>
#include <kernel/thread.h>
#include <kernel/timer.h>

#define THREAD_CHECKS 1

/* global thread list */
static struct list_node thread_list;

/* the current thread */
struct thread *current_thread;

/* the run queue */
static struct list_node run_queue[NUM_PRIORITIES];

/* the idle thread */
static struct thread *idle_thread;

/* local routines */
static void thread_resched(void);

/* run queue manipulation */
static void insert_in_run_queue_head(struct thread *t)
{
#if THREAD_CHECKS
	ASSERT(t->magic == THREAD_MAGIC);
	ASSERT(t->state == THREAD_READY);
	ASSERT(!list_in_list(&t->queue_node));
	ASSERT(in_critical_section());
#endif

	list_add_head(&run_queue[t->priority], &t->queue_node);
}

static void insert_in_run_queue_tail(struct thread *t)
{
#if THREAD_CHECKS
	ASSERT(t->magic == THREAD_MAGIC);
	ASSERT(t->state == THREAD_READY);
	ASSERT(!list_in_list(&t->queue_node));
	ASSERT(in_critical_section());
#endif

	list_add_tail(&run_queue[t->priority], &t->queue_node);
}

static struct thread *create_thread_struct(const char *name)
{
	struct thread *t;

	t = malloc(sizeof(struct thread));
	if (!t)
		return NULL;

	memset(t, 0, sizeof(struct thread));
	t->magic = THREAD_MAGIC;
	strlcpy(t->name, name, sizeof(t->name));

	return t;
}

struct thread *thread_create(const char *name, thread_start_routine entry, void *arg, int priority, size_t stack_size)
{
	struct thread *t;

	t = create_thread_struct(name);
	if (!t)
		return NULL;

	t->entry = entry;
	t->arg = arg;
	t->priority = priority;
	t->critical_section_count = 1; /* we always start inside a critical section */
	t->state = THREAD_SUSPENDED;

	/* create the stack */
	t->stack = malloc(stack_size);
	if (!t->stack) {
		free(t);
		return NULL;
	}

	t->stack_size = stack_size;

	/* set up the initial stack frame */
	arch_thread_initialize(t);

	/* add it to the global thread list */
	enter_critical_section();
	list_add_head(&thread_list, &t->thread_list_node);
	exit_critical_section();

	return t;
}

status_t thread_resume(struct thread *t)
{
#if THREAD_CHECKS
	ASSERT(t->magic == THREAD_MAGIC);
#endif

	if (t->state == THREAD_READY || t->state == THREAD_RUNNING)
		return ERR_NOT_SUSPENDED;

	enter_critical_section();
	t->state = THREAD_READY;
	insert_in_run_queue_head(t);
	thread_yield();
	exit_critical_section();

	return NO_ERROR;
}

void thread_exit(int retcode)
{
#if THREAD_CHECKS
	ASSERT(current_thread->magic == THREAD_MAGIC);
	ASSERT(current_thread->state == THREAD_RUNNING);
#endif

//	dprintf("thread_exit: current %p\n", current_thread);

	enter_critical_section();

	/* enter the dead state */
	current_thread->state = THREAD_DEATH;
	current_thread->retcode = retcode;

	/* reschedule */
	thread_resched();

	panic("somehow fell through thread_exit()\n");
}

static int idle_thread_routine(void *arg)
{
	for(;;)
		;
	return 0;
}

/* 
 * Internal reschedule routine. The current thread needs to already be in whatever
 * state and queues it needs to be in. This routine simply picks the next thread and
 * switches to it.
 */
void thread_resched(void)
{
	int i;
	struct thread *oldthread;
	struct thread *newthread;

//	dprintf("thread_resched: current %p: ", current_thread);
//	dump_thread(current_thread);

#if THREAD_CHECKS
	ASSERT(in_critical_section());
#endif

	oldthread = current_thread;

	// XXX make this more efficient
	newthread = NULL;
	for (i=HIGHEST_PRIORITY; i >= LOWEST_PRIORITY; i--) {
		newthread = list_remove_head_type(&run_queue[i], struct thread, queue_node);
		if (newthread)
			break;
	}

	/* it should at least find the idle thread */
	ASSERT(newthread);

//	dprintf("newthread: ");
//	dump_thread(newthread);

	newthread->state = THREAD_RUNNING;

	if (newthread == oldthread)
		return;

	/* do the switch */
	current_thread = newthread;
	arch_context_switch(oldthread, newthread);
}

void thread_yield(void)
{
#if THREAD_CHECKS
	ASSERT(current_thread->magic == THREAD_MAGIC);
	ASSERT(current_thread->state == THREAD_RUNNING);
#endif

	enter_critical_section();

	/* we are yielding the cpu, so stick ourselves into the tail of the run queue and reschedule */
	current_thread->state = THREAD_READY;
	insert_in_run_queue_tail(current_thread);
	thread_resched();

	exit_critical_section();
}

void thread_preempt(void)
{
#if THREAD_CHECKS
	ASSERT(current_thread->magic == THREAD_MAGIC);
	ASSERT(current_thread->state == THREAD_RUNNING);
#endif

	enter_critical_section();

	/* we are being preempted, so we get to go back into the front of the run queue */
	current_thread->state = THREAD_READY;
	insert_in_run_queue_head(current_thread);
	thread_resched();

	exit_critical_section();
}

void thread_block(void)
{
#if THREAD_CHECKS
	ASSERT(current_thread->magic == THREAD_MAGIC);
	ASSERT(current_thread->state == THREAD_BLOCKED);
#endif

	enter_critical_section();

	/* we are blocking on something. the blocking code should have already stuck us on a queue */
	thread_resched();

	exit_critical_section();
}

/* timer tick to wake up a sleeping thread */
static enum handler_return thread_sleep_handler(struct timer *timer, time_t now, void *arg)
{
	struct thread *t = (struct thread *)arg;

#if THREAD_CHECKS
	ASSERT(t->magic == THREAD_MAGIC);
	ASSERT(t->state == THREAD_SLEEPING);
#endif

	t->state = THREAD_READY;
	insert_in_run_queue_head(t);

	return INT_RESCHEDULE;
}

void thread_sleep(time_t delay)
{
	struct timer timer;

#if THREAD_CHECKS
	ASSERT(current_thread->magic == THREAD_MAGIC);
	ASSERT(current_thread->state == THREAD_RUNNING);
#endif

	timer_initialize(&timer);

	enter_critical_section();
	timer_set_oneshot(&timer, delay, thread_sleep_handler, (void *)current_thread);
	current_thread->state = THREAD_SLEEPING;
	thread_resched();
	exit_critical_section();
}

void thread_init(void)
{
	int i;

	/* initialize the run queues */
	for (i=0; i < NUM_PRIORITIES; i++)
		list_initialize(&run_queue[i]);

	/* initialize the thread list */
	list_initialize(&thread_list);

	/* create a thread to cover the current running state */
	struct thread *t = create_thread_struct("bootstrap");

	/* half construct this thread, since we're already running */
	t->priority = HIGHEST_PRIORITY;
	t->state = THREAD_RUNNING;
	t->critical_section_count = 1;
	list_add_head(&thread_list, &t->thread_list_node);
	current_thread = t;

	/* make an idle thread */
	idle_thread = thread_create("idle", &idle_thread_routine, NULL, IDLE_PRIORITY, 512);
	thread_resume(idle_thread);
}

void dump_thread(struct thread *t)
{
	dprintf("dump_thread: t %p (%s)\n", t, t->name);
	dprintf("\tstate %d, priority %d, critical section %d\n", t->state, t->priority, t->critical_section_count);
	dprintf("\tstack %p, stack_size %zd\n", t->stack, t->stack_size);
	dprintf("\tentry %p, arg %p\n", t->entry, t->arg);
}

/* wait queue */
void wait_queue_init(struct wait_queue *wait)
{
	wait->magic = WAIT_QUEUE_MAGIC;
	list_clear_node(&wait->list);
	wait->count = 0;
}

void wait_queue_block(struct wait_queue *wait)
{
#if THREAD_CHECKS
	ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
	ASSERT(current_thread->state == THREAD_RUNNING);
#endif

	enter_critical_section();
	list_add_tail(&wait->list, &current_thread->queue_node);
	wait->count++;
	current_thread->state = THREAD_BLOCKED;
	thread_block();
	exit_critical_section();
}

int wait_queue_wake_one(struct wait_queue *wait, bool reschedule)
{
	struct thread *t;
	int ret = 0;

#if THREAD_CHECKS
	ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
#endif

	enter_critical_section();
	t = list_remove_head_type(&wait->list, struct thread, queue_node);
	if (t) {
		wait->count--;
		t->state = THREAD_READY;

		/* if we're instructed to reschedule, stick the current thread on the head
		 * of the run queue first, so that the newly awakened thread gets a chance to run
		 * before the current one, but the current one doesn't get unnecessarilly punished.
		 */
		if (reschedule) {
			current_thread->state = THREAD_READY;
			insert_in_run_queue_head(current_thread);
		}
		insert_in_run_queue_head(t);
		if (reschedule)
			thread_resched();
		ret = 1;
	}
	exit_critical_section();

	return ret;
}

int wait_queue_wake_all(struct wait_queue *wait, bool reschedule)
{
	struct thread *t;
	int ret = 0;

#if THREAD_CHECKS
	ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
#endif

	enter_critical_section();

	if (reschedule && wait->count > 0) {
		/* if we're instructed to reschedule, stick the current thread on the head
		 * of the run queue first, so that the newly awakened threads get a chance to run
		 * before the current one, but the current one doesn't get unnecessarilly punished.
		 */
		current_thread->state = THREAD_READY;
		insert_in_run_queue_head(current_thread);
	}

	/* pop all the threads off the wait queue into the run queue */
	while ((t = list_remove_head_type(&wait->list, struct thread, queue_node))) {
		wait->count--;
		t->state = THREAD_READY;

		insert_in_run_queue_head(t);
		ret++;
	}

#if THREAD_CHECKS
	ASSERT(wait->count == 0);
#endif

	if (reschedule && ret > 0)
		thread_resched();

	exit_critical_section();

	return ret;
}

void wait_queue_destroy(struct wait_queue *wait, bool reschedule)
{
#if THREAD_CHECKS
	ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
#endif
	wait_queue_wake_all(wait, reschedule);
	wait->magic = 0;
}

