/*
 * RTC.c
 *
 *  Created on: Dec 23, 2011
 *      Author: RomanM
 */

#include <inttypes.h>
#include "hal_RTC.h"

struct DateTime {
	unsigned Year	: 12;
	unsigned Month	: 4;
	unsigned Day	: 5;
	unsigned Hour	: 5;
	unsigned Minute	: 6;
	unsigned Second	: 6;
} DateTime = {2000, 1, 1, 0, 0, 0};

char *dayNames[] = {
	"Nedela",
	"Pondelok",
	"Utorok",
	"Streda",
	"Stvrtok",
	"Piatok",
	"Sobota"
};

void RTC_Init(void) {
	hal_RTC_Init();
}

/*
 * RTC 1 second interrupt handler
 */
void RTC_InterruptHandler(void) {
	DateTime.Second ++;
	if(DateTime.Second >= 60) {
		DateTime.Second = 0;
		DateTime.Minute ++;
		if (DateTime.Minute >= 60) {
			DateTime.Minute = 0;
			DateTime.Hour++;
			if (DateTime.Hour >= 24) {
				DateTime.Hour = 0;

				DateTime.Day++;
				if (DateTime.Month == 4 ||
					DateTime.Month == 6 ||
					DateTime.Month == 9 ||
					DateTime.Month == 11) {

					if (DateTime.Day == 30) {
						DateTime.Day = 0;
						DateTime.Month++;
					}
				}
				else if (DateTime.Month == 2) {
					if (DateTime.Year % 4 == 0 && (DateTime.Year % 100 != 0 || DateTime.Year % 400 == 0)) {
						if (DateTime.Day == 29) {
							DateTime.Day = 0;
							DateTime.Month++;
						}
					}
					else if (DateTime.Day == 28) {
						DateTime.Day = 0;
						DateTime.Month++;
					}
				}
				else if (DateTime.Day == 31) {
					DateTime.Day = 0;
					DateTime.Month++;
				}

				if (DateTime.Month > 12) {
					DateTime.Month = 1;
					DateTime.Year++;
				}
			}
		}
	}
}

/*
 * Getting time
 */

uint16_t RTC_GetYear(void) {
	return DateTime.Year;
}

uint8_t RTC_GetMonth(void) {
	return DateTime.Month;
}

uint8_t RTC_GetDay(void) {
	return DateTime.Day;
}

uint8_t RTC_GetHour(void) {
	return DateTime.Hour;
}

uint8_t RTC_GetMinute(void) {
	return DateTime.Minute;
}

uint8_t RTC_GetSecond(void) {
	return DateTime.Second;
}

uint8_t RTC_GetDayOfWeek(void) {
	static uint8_t t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
	uint16_t y = DateTime.Year;

	y -= DateTime.Month < 3;
	return (y + y/4 - y/100 + y/400 + t[DateTime.Month-1] + DateTime.Day) % 7;
}



/*
 * Setting time
 */

void RTC_SetYear(uint16_t year) {
	DateTime.Year = year;
}

void RTC_SetMonth(uint8_t month) {
	DateTime.Month = month;
}

void RTC_SetDay(uint8_t day) {
	DateTime.Day = day;
}

void RTC_SetHour(uint8_t hour) {
	DateTime.Hour = hour;
}

void RTC_SetMinute(uint8_t minute) {
	DateTime.Minute = minute;
}

void RTC_SetSecond(uint8_t second) {
	DateTime.Second = second;
}
