#include "rtk32.h"
#include "rttarget.h"
#include "Cpumoni.h"
#include "windows.h"
#include "rttextio.h"
#include "rtkeybrd.h"
#include "clock.h"

#include "processer.h"

// TRYK PÅ KNAP
Proc_KnapTrykTaeller::Proc_KnapTrykTaeller(RTKSemaphore *tryk, KnapTaeller *kt) {
	this->tryk = tryk;
	this->kt = kt;
	this->antal = 0;
}

void Proc_KnapTrykTaeller::run() {
	int tmp;
	while ( true ) {
		RTKWait( *(this->tryk) );
		tmp = kt->aktuelVaerdi();
		kt->opdater(tmp+1);
	}
}

// VIS ANTAL KNAP TRYK
#define COLOR_VISKNAP 0xB
Proc_VisKnapTryk::Proc_VisKnapTryk(RTKSemaphore *tryk, KnapTaeller *kt) {
	this->tryk = tryk;
	this->kt = kt;
}

void Proc_VisKnapTryk::run() {
	WWindow *win = WNewWindow(5, 12, 36, 17, 500, COLOR_VISKNAP, "Proc_VisKnapTryk");
	while (true) {
		WGotoXY(win,0,0);
		RTKWaitCond( *(this->tryk) );
		Wprintf( win, "%3d Antal tryk\r\n", kt->aktuelVaerdi() );
		RTKDelay(10);	// Vent 1 sekund. // 0,1 sek
	}
}

// TIMER
Proc_Timer::Proc_Timer(RTKSemaphore *sem) {
	this->sem = sem;
}

void Proc_Timer::run() {
	while (true) {
		RTKDelay(10);	// 0,1 sek
		RTKSignal( *(this->sem) );
	}
}

// VIS AKTUEL TID
#define COLOR_UR 0xC
Proc_Ur::Proc_Ur(RTKSemaphore *timer) {
	this->timer = timer;
}

void Proc_Ur::run() {
	SYSTEMTIME t;
	WWindow *win = WNewWindow(42, 12, 74, 17, 500, COLOR_UR, "Proc_Ur"); 
	while (true) {
		RTKWait( *(this->timer) );		
		RTCMOSReadTime(&t);
		WGotoXY(win,0,0);
		Wprintf(win, "Tid: %1d%1d:%1d%1d:%1d%1d \n",
			t.wHour / 10, t.wHour % 10,
			t.wMinute / 10, t.wMinute % 10,
			t.wSecond / 10,t.wSecond % 10);
	}
}

// INLÆS DATA
#define COLOR_Proc_Operator 0xD
#define S_LEN 2
Proc_Operator::Proc_Operator(RTKSemaphore *sem, KnapTaeller *kt) {
	this->sem = sem;
	this->kt = kt;
}

void Proc_Operator::run() {
	char s[S_LEN];
	WWindow *win = WNewWindow(5, 2, 36, 10, 500, COLOR_Proc_Operator, "Proc_Operator");
	WSetUserInput(KBGetCh); // input fra keyboard
	Wprintf(win, "E: exit\nN: nulstil antal tryk\nS: Indstil ur\n");
	while (true) {
		WGotoXY(win,0,3);
		Wprintf(win, "Indtast kommando:  ");
		WGotoXY(win,18,3);
		
		WGetS(win, s, S_LEN);
		switch (s[0]) {
			case 'E':
				RTKSignal( *(this->sem) );
				Wprintf(win, "                 ");
				break;
			case 'N':
				this->kt->nulstil();
				Wprintf(win, "Tæller nulstillet");				
				break;
			case 'S':
				Wprintf(win, "Indtast tiden");
				break;
			default:
				Wprintf(win, "Forkert!         ");
		}
	}
}

// CPU MONITOR
#define COLOR_MONITOR 0xE
Proc_Monitor::Proc_Monitor() {
	CPUMonitorStart( CPU_IDLE_TASK );
}

void Proc_Monitor::run() {
//	5, 2, 36, 10
//	43, 12, 74, 16
	WWindow *win = WNewWindow(42, 2, 74, 10, 500, COLOR_MONITOR, "Proc_Monitor");
	while (true) {
		WGotoXY(win,0,0);
		Wprintf(win, "     ");
		WGotoXY(win,0,0);
		Wprintf(win, "%d %%", CPURelativeLoad(100) );

		RTKDelay(300); // Vent 3 sekunder
	}
}