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

#include "io686.h"
#include "logfile.hpp"

#include "procLED.h"
#include "procSwitch.h"
#include "procOperator.h"
#include "procFrekvens.h"
#include "procVisLog.h"

#define MB_LEN 4

void main() {
	/* DEFAULT */
	RTKernelInit(3); // proces main får prioritet 3
	RTKPreemptionsON(); // preemptiv skedulering
	CLKSetTimerIntVal(10000); // systemtidsenhed == 10 msek
	KBInit(); // initiering af keyboard
	RTInitMouse(-1, 12, 0, 5, 5); // initiering af mus
	WClearScreen(0x7);
	/* END DEFAULT */

	RTKSemaphore sem_stop = RTKCreateSemaphore(ST_COUNTING, 0, "mainStop");
	RTKSemaphore knap_switch = RTKCreateSemaphore(ST_COUNTING, 0, "knapSwitch");

	RTKMailbox mb_led_op = RTKCreateMailbox( sizeof ( char ), MB_LEN, "mb_led_op");
	RTKMailbox mb_vis_op = RTKCreateMailbox( sizeof ( char ), MB_LEN, "mb_vis_op");

	LEDPort *LP = new LEDPort;
	SwitchPort *SP = new SwitchPort;
	Timer *T = new Timer(Timer::TIMER_1,Timer::MODE_3);
	PPI *P = new PPI(PPI::INPUT,PPI::INPUT,PPI::INPUT);
	Log *log = new Log("logfil.txt");

	#define COLOR_MAIN 0xA
	WWindow *winMain = WNewWindow(5, 19, 36, 23, 500, COLOR_MAIN, " Main: ");
	Wprintf(winMain, "Proces Main startet\n");

	procVisLog vl( &mb_vis_op, log );
	RTKRTLCreateThread(Thread::threadMapper, 4, 0, 0, &vl, "Proc_VisLog");

	procLED led( &mb_led_op, LP, log);
	RTKRTLCreateThread(Thread::threadMapper, 4, 0, 0, &led, "Proc_Led");

	procOperator op( &mb_led_op, &mb_vis_op, &sem_stop , log);
	RTKRTLCreateThread(Thread::threadMapper, 4, 0, 0, &op, "Proc_Operator");

	procSwitch sw( &knap_switch, SP, log);
	RTKRTLCreateThread(Thread::threadMapper, 4, 0, 0, &sw, "Proc_Switch");

	procFrekvens fre( T, P, log );
	RTKRTLCreateThread(Thread::threadMapper, 4, 0, 0, &fre, "Proc_Frekvens");

	RTKWait(sem_stop);
	LogData ld("Systemet lukkes");
	log->skriv(ld);
	Wprintf(winMain, "Stop modtaget\n");
}
