/*
			negiman

	1/10 このプログラムもCPU使用率上昇の原因
		 だということが発覚。clock.cと同じ原理でCPU使用率を抑えています by is2os

*/
#include "bootpack.h"
#include <stdio.h>
#include <string.h>

struct SHEET *open_taskman(struct SHTCTL *shtctl, unsigned int memtotal) 
{
	const int window_w = 260, window_h = 280;
	struct MEMMAN *memman = (struct MEMMAN *)MEMMAN_ADDR;
	struct SHEET *sht = sheet_alloc(shtctl); 
	unsigned char *buf = (unsigned char *)memman_alloc_4k(memman, window_w * window_h);
	struct TASK *task = task_alloc();
	sht->flags |= SHEET_NEGIMAN_FLAGS;
	sheet_setbuf(sht, buf, window_w, window_h, -1);
	make_window8(buf, window_w, window_h, "Negi Maneger", 0);
	task->ds_base = memman_alloc_4k(memman, 64 * 1024);
	task->tss.esp = task->ds_base + 64 * 1024 - 4;
	task->tss.eip = (int)&taskman_task;
	task->tss.es = 1 * 8;
	task->tss.cs = 2 * 8;
	task->tss.ss = 1 * 8;
	task->tss.ds = 1 * 8;
	task->tss.fs = 1 * 8;
	task->tss.gs = 1 * 8;
	*((int *)(task->tss.esp + 4)) = (int)sht;
	task_run(task, 4, 2, "negiman");	/* ここの優先度は具合に応じて変更 */
	sht->task = task;
	return sht;
}

void close_taskman(struct SHEET *sht, struct TASK *task, unsigned long mem) 
{
	struct MEMMAN *memman = (struct MEMMAN *)MEMMAN_ADDR;
	memman_free_4k(memman, task->ds_base, 64 * 1024);
	task_sleep(sht->task);
	sht->task->flags = 0;
	memman_free_4k(memman, (int)sht->buf, mem);
	sheet_free(sht);	
	return;
}

typedef struct task_name { char name[40]; } TASK_STRING;

void taskman_task(struct SHEET *sht)
{
	TASK_STRING tasks[MAX_TASKS];
	int i;

	for (;;) {
		boxfill8(sht->buf, sht->bxsize, COL8_000000, 10, 48, 250, 265);
		putfonts8_asc(sht->buf, sht->bxsize, 18, 30, COL8_000000, 
						"Num   Name     Lv  Pri  flg");
		
		/* 動作中のタスクの情報を取得 */
		for (i = 0;i < 11;i++) {
			if (taskctl->tasks0[i].flags <= 0) continue;
			sprintf(tasks[i].name, "%d", i);
			putfonts8_asc(sht->buf, sht->bxsize, 25, 50 + (i * 20), /*COL8_FF0000*/2, tasks[i].name);
			sprintf(tasks[i].name, "%s", taskctl->tasks0[i].tasknm);
			putfonts8_asc(sht->buf, sht->bxsize, 55, 50 + (i * 20), /*COL8_FF0000*/2, tasks[i].name);
			sprintf(tasks[i].name, "%d", taskctl->tasks0[i].level);
			putfonts8_asc(sht->buf, sht->bxsize, 145, 50 + (i * 20), /*COL8_FF0000*/2, tasks[i].name);
			sprintf(tasks[i].name, "%d", taskctl->tasks0[i].priority);
			putfonts8_asc(sht->buf, sht->bxsize, 175, 50 + (i * 20), /*COL8_FF0000*/2, tasks[i].name);
			sprintf(tasks[i].name, "%d", taskctl->tasks0[i].flags);
			putfonts8_asc(sht->buf, sht->bxsize, 215, 50 + (i * 20), /*COL8_FF0000*/2, tasks[i].name);			
		}

		sheet_refresh(sht, 0, 0, 260, 280);

		/* CPU使用率を抑えるため */
		io_hlt();
	}
	return;
}

