/*
Copyright 2003/2004, 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.
Contributors: Thomas Pietsch, Bjoern Lichtblau

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

/** \file time.c
 ** \ingroup Firmware
 ** \brief This file is the software RTC.
 **
 ** This file keeps the global time of this node in the global var currentTime.
 ** It contains methods for writing, reading and converting currentTime.<br>
 ** To avoid concurrency problems accessing currentTime must be done with disabled interrupts
 ** or in interrupt routines only. time.h defines some macro for accessing ::currentTime safely.  
 **
 **/
 
#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)

/** \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 getCurrentTime and setCurrentTime
 * 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;

/** \brief Read currentTime or safely with disabled interrupts. 
 *
 * Easier (and also faster) to use is CURRENT_TIME:
 * time_t time = CURRENT_TIME; <-> time_t time; getCurrentTime(&time); 
 **/
bool Time_getSystemTime(time_t* time){
  dint();
  _NOP();
  *time = currentTime;
  eint();  
  return True;
}

/** \brief Write currentTime or safely with disabled interrupts. */
bool Time_setSystemTime(time_t* time){
  dint();
  _NOP();
  currentTime = *time;
  eint();
  return True;
}

/// 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); }

/** \brief Converts time to broken down time, see type declarations in time.h */
bool Time_convertSystemTime(const time_t* src, btime_t* dst){
  UINT32 minutes = src->secs / 60; // absolute minutes since 1.3.00
  UINT32 hours = minutes / 60;     // absolute hours since 1.3.00
  UINT16 days = hours / 24;       // absolute days since 1.3.00
  UINT16 y4;                        // absolute 4yearcycle with leapday (4*365)+1=1461 days periods
  UINT16 tmp;
  UINT16 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++;
  //print("days: %i y4: %i dd4: %i dm4: %i\r\n", days, y4, dd4, dm4);
  CHECKMONTH(JAN, 1);
  CHECKMONTH(feb, 2);
  CHECKMONTH(MAR, 3);
  CHECKMONTH(APR, 4);
  CHECKMONTH(MAY, 5);
  CHECKMONTH(JUN, 6);
  CHECKMONTH(JUL, 7);
  CHECKMONTH(AUG, 8);
  CHECKMONTH(SEP, 9);
  CHECKMONTH(OCT, 10);
  CHECKMONTH(NOV, 11);
  CHECKMONTH(DEC, 12);
  return True;
}

/** \brief Converts broken down time to time, see type declarations in time.h */
bool Time_convertTime(const btime_t* src, time_t* dst){
  UINT32 secs;
  UINT16 feb;
  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: secs += (86400)*(src->day - 1); break;
    case  2: secs += (86400)*(JAN + (src->day - 1)); break;
    case  3: secs += (86400)*(JAN + feb + (src->day - 1)); break;
    case  4: secs += (86400)*(JAN + feb + MAR + (src->day - 1)); break;
    case  5: secs += (86400)*(JAN + feb + MAR + APR + (src->day - 1)); break;
    case  6: secs += (86400)*(JAN + feb + MAR + APR + MAY + (src->day - 1)); break;
    case  7: secs += (86400)*(JAN + feb + MAR + APR + MAY + JUN + (src->day - 1)); break;
    case  8: secs += (86400)*(JAN + feb + MAR + APR + MAY + JUN + JUL + (src->day - 1)); break;
    case  9: secs += (86400)*(JAN + feb + MAR + APR + MAY + JUN + JUL + AUG +(src->day - 1)); break;
    case 10: secs += (86400)*(JAN + feb + MAR + APR + MAY + JUN + JUL + AUG + SEP + (src->day - 1)); break;
    case 11: secs += (86400)*(JAN + feb + MAR + APR + MAY + JUN + JUL + AUG + SEP + OCT + (src->day - 1)); break;
    case 12: secs += (86400)*(JAN + feb + MAR + APR + MAY + JUN + JUL + AUG + SEP + OCT + NOV + (src->day - 1)); break;
  }
  // add hour minute second
  secs += ((((UINT32)src->hour * 60) + src->min) * 60) + src->sec;
  // write dest
  dst->secs = secs;
  dst->millis = 0;
  return True;
}

/** \brief Writes broken down time as a string in the form yyyy-mm-dd hh:mm:ss */
bool Time_writeTime(fp_char_t writer, btime_t* time){
  UINT16 year = 2000 + time->year;
  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;
}

/** \brief Reads broken down time as a string.
 **
 ** The format is the same as in writeTime, but the year must be written
 ** without 2000. The number of digits is not fixed like in writeTime,
 ** so it is ok to write 03-09-07 08:31:02 or 3-9-7 8:31:2.
 */ 
bool Time_readTime(const UINT8* c, btime_t* time){
  UINT8* p = (UINT8*) c;
  time->year = String_parseInt(p, &p); p++;
  time->month = String_parseInt(p, &p); p++;
  time->day = String_parseInt(p, &p); p++;
  time->hour = String_parseInt(p, &p); p++;
  time->min = String_parseInt(p, &p); p++;
  time->sec = String_parseInt(p, &p);
  return True;
}
