/*
Copyright 2007, Freie Universitaet Berlin. All rights reserved.

These sources were developed at the Freie Universität Berlin, Computer
Systems and Telematics group.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
 
- Neither the name of Freie Universitaet Berlin (FUB) nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

This software is provided by FUB and the contributors on an "as is"
basis, without any representations or warranties of any kind, express
or implied including, but not limited to, representations or
warranties of non-infringement, merchantability or fitness for a
particular purpose. In no event shall FUB or contributors be liable
for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of
substitute goods or services; loss of use, data, or profits; or
business interruption) however caused and on any theory of liability,
whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even
if advised of the possibility of such damage.

This implementation was developed by the CST group at the FUB.

For documentation and questions please use the web site
http://scatterweb.mi.fu-berlin.de and the mailinglist
scatterweb@lists.spline.inf.fu-berlin.de (subscription via the Website).
Berlin, 2007
*/

#include "ScatterWeb.System.h"

// Days per Month
#define JAN   (31)
#define FEB   (28)
#define MAR   (31)
#define APR   (30)
#define MAY   (31)
#define JUN   (30)
#define JUL   (31)
#define AUG   (31)
#define SEP   (30)
#define OCT   (31)
#define NOV   (30)
#define DEC   (31)

static const uint8_t days_per_month[12] = {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

/*
 *   brief This represents the RTC and consists of a 32 bit second counter and a
 *   10 bit millisecond counter.
 *
 *   currentTime gets incremented by the Timer_A0 Interrupt in timer.c
 *   To avoid interference with interrupts one should use Time_get and Time_set
 *   to write and read the time (or macros CURRENT_TIME, CURRENT_TIME_SECS). For that reason
 *   this var isn't declared public in the header file.
 */
volatile time_t currentTime;

void Time_init() {
  // set current time to compile time of application
  // (run from main init before switching on interrupts)
  currentTime.secs =  appHeader.compileTime;
  currentTime.secs -= UTC_OFFSET_SECONDS;
  currentTime.millis = 0;
}

time_t* Time_get(time_t* time) {
  dint();
  _NOP();
  *time = currentTime;
  eint();  
  return time;
}

bool Time_set(time_t* time) {
  dint();
  _NOP();
  currentTime = *time;
  eint();
  return True;
}

bool Time_convertTime(const time_t* src, btime_t* dst) {
  // Local macro to distribute days over the year.
  #define CHECKMONTH(x, m)   if(dm4 < (x)){dst->month = (m); dst->day = 1 + dm4; return True; } \
                           else { dm4 -= (x); }

  uint32_t minutes = src->secs / 60; // absolute minutes since 1.3.00
  uint32_t hours = minutes / 60;     // absolute hours since 1.3.00
  uint16_t days = hours / 24;        // absolute days since 1.3.00
  uint16_t y4;                       // absolute 4yearcycle with leapday (4*365)+1=1461 days periods
  uint16_t tmp;
  uint16_t dd4, dm4, feb;
  
  dst->sec = src->secs % 60;
  dst->min = minutes % 60;
  dst->hour = hours % 24;
  y4 = days / 1461;
  dst->year = 1 + 4*(y4);
  dst->month = 01;
  dst->day = 01;
  tmp = days % 1461; // tmp has now the remaining 1461 days to add on year,month,day
  dd4 = tmp / 365;
  dm4 = tmp % 365;
  if(dd4==4) {
    dm4 = 365;
    dd4 = 3;
  }
  dst->year += dd4;
  feb = FEB;
  if(dd4==3) feb++;
  
  CHECKMONTH(JAN, 1);
  CHECKMONTH(feb, 2);
  for( tmp = 2; tmp < 12; tmp++ ) {
  	CHECKMONTH(days_per_month[tmp], tmp + 1);
  }
  return True;
}

bool Time_convertBtime(const btime_t* src, time_t* dst) {
  uint32_t secs;
  uint16_t feb;
  uint16_t i;
  uint32_t mult;
  
  secs = (86400*365) * (src->year - 1); //add years to seconds
  secs += (86400*((src->year-1)/4));    //add leap year days
  feb = FEB;                            //choose feb 28 or 29
  if((src->year % 4) == 0) feb++;
  switch(src->month) {                  // add month and day
    case  1:
    	mult = 0;
    	break;
    case  2:
    	mult = JAN;
    	break;
    default:
    	mult = JAN + feb;
    	for( i = 2; i < (src->month - 1); i++ )
    		mult += days_per_month[i];
  }
  mult += src->day - 1;
  secs += 86400 * mult;
  // add hour minute second
  secs += ((((uint32_t)src->hour * 60) + src->min) * 60) + src->sec;
  // write dest
  dst->secs = secs;
  dst->millis = 0;
  return True;
}

bool Time_write(char* buffer, btime_t* time) {
	uint16_t year = 2000 + time->year;
	sprintf(buffer, "%.4u-%.2u-%.2u#%.2u:%.2u:%.2u",
			year, time->month, time->day,
			time->hour, time->min, time->sec);
/*
  String_writeUInt(writer, year, 4);
  writer('-');
  String_writeUInt(writer, time->month, 2);
  writer('-');
  String_writeUInt(writer, time->day, 2);
  writer('#');
  String_writeUInt(writer, time->hour, 2);
  writer(':');
  String_writeUInt(writer, time->min, 2);
  writer(':');
  String_writeUInt(writer, time->sec, 2);
*/
  return True;
}

bool Time_read(const uint8_t* c, btime_t* time) {
  char* p = (char*)c;
  uint16_t year = strtoul(p, &p, 10); p++;
  if( year > 2000 )
	year -= 2000;
  if( year > 255 ) 
	return false;
	
  time->year = year;
  time->month = strtoul(p, &p, 10); p++;
  if( time->month == 0 ) time->month = 1;
  time->day = strtoul(p, &p, 10); p++;
  if( time->day == 0 ) time->day = 1;
  time->hour = strtoul(p, &p, 10); p++;
  time->min = strtoul(p, &p, 10); p++;
  time->sec = strtoul(p, &p, 10);
  
  return true;
}
