#include "dateTime.h"

dateTime_t private_dateTime;

void dateTime_init(void) {
    private_dateTime.months  = 0;
    private_dateTime.days    = 0;
    private_dateTime.hours   = 0;
    private_dateTime.minutes = 0;
    private_dateTime.seconds = 0;
    
    T1CONbits.T1OSCEN = 1;  // timer1 oscillator enabled
    T1CONbits.TMR1CS = 2;   // timer1 oscillator as clock source
    T1CONbits.T1CKPS = 0;   // no prescaler
    T1CONbits.nT1SYNC = 1;  // asynchronous mode (needed for sleep mode)

    T1CONbits.TMR1ON = 1;   // start timer1
    while (T1OSCR == 0);    // wait until timer1 oscillator is running
    
    TMR1L = 0;  // reset timer1 value
    TMR1H = 0;
    TMR1IF = 0; // reset timer1 interrupt flag
    TMR1IE = 1; // enable timer1 interrupt
    PEIE = 1;   // enable global interrupt
    GIE = 1;
}


void dateTime_update(void) {
    private_dateTime.seconds +=2;
    if (private_dateTime.seconds > 59) {
        private_dateTime.seconds = 0;
        if (++private_dateTime.minutes > 59) {
            private_dateTime.minutes = 0;
            if (++private_dateTime.hours > 23) {
                private_dateTime.hours = 0;
                if (++private_dateTime.days > 30) {
                    private_dateTime.days = 0;
                    private_dateTime.months++;
                }
            }
        }
    }
}


int8_t dateTime_isMidnight(void) {
    return ( (private_dateTime.seconds == 0) &&
             (private_dateTime.minutes == 0) &&
             (private_dateTime.hours == 0) );
}

/*
int8_t dateTime_isNewMonth(void) {
    return ( (private_dateTime.seconds == 0) &&
             (private_dateTime.minutes == 0) &&
             (private_dateTime.hours == 0)  &&
             (private_dateTime.days == 0) );
}*/

int8_t dateTime_isNewMonth(void) {
    return ( (private_dateTime.seconds == 0) &&
             (private_dateTime.minutes%10 == 0) );
}

dateTime_t dateTime_get(void) {
    return(private_dateTime);
}

int8_t dateTime_compare(dateTime_t date1, dateTime_t date2) {
    int8_t success = 1;
    
    if (date1.months != date2.months) {
        success = 0;
    } else     if (date1.months != date2.months) {
        success = 0;
    } else if (date1.days != date2.days) {
        success = 0;
    } else if (date1.hours != date2.hours) {
        success = 0;
    } else if (date1.minutes != date2.minutes) {
        success = 0;
    } else if (date1.seconds != date2.seconds) {
        success = 0;
    }
    return (success);
}
