#include "watch_registers.h"

// leave resource_detector.h as last include!
#include "resource_detector.h"

void watch_registers_toggle_config_is_paused(uint8_t* config){
    *config ^= 0x08; // Toggle the 4th bit 0x08 = 0b00001000
}
void watch_registers_set_config_time_format(uint8_t* config, time_format format){
    *config = (*config & 0x0E) | format;
}
void watch_registers_set_config_time_update_interval(uint8_t* config, time_update_interval interval){
    *config = (*config & 0xF9) | (interval << 1); // Clear bits 2 and 3 and set them to the new value: 0x06 = 0b00000110
}
void watch_registers_get_config_settings(uint8_t config, bool* is_paused, time_format* format, time_update_interval* interval){
    *is_paused = (config & 0x08);
    *format = (config & 0x01);
    *interval = ((config >> 1) & 0x03);
}

void watch_registers_set_time_hours(uint8_t* time_bits_low, uint8_t* time_bits_high, uint8_t hours){
    *time_bits_high = (*time_bits_high & 0x0F) | ((hours & 0x0F) << 4); // Set the upper nibble
}
void watch_registers_set_time_minutes(uint8_t* time_bits_low, uint8_t* time_bits_high, uint8_t minutes){
    *time_bits_high = (*time_bits_high & 0xF0) | ((minutes >> 2) & 0x0F); // Set the lower nibble of MSB
    *time_bits_low = (*time_bits_low & 0x3F) | ((minutes & 0x03) << 6);  // Set the upper two bits of LSB
}
void watch_registers_set_time_seconds(uint8_t* time_bits_low, uint8_t* time_bits_high, uint8_t seconds){
    *time_bits_low = (*time_bits_low & 0xC0) | (seconds & 0x3F); // Set the lower 6 bits of LSB
}
void watch_registers_get_time(uint8_t time_bits_low, uint8_t time_bits_high, uint8_t* hours, uint8_t* minutes, uint8_t* seconds){
    *hours = (time_bits_high >> 4) & 0x0F; 
    *minutes = ((time_bits_high & 0x0F) << 2) | ((time_bits_low >> 6) & 0x03); 
    *seconds = time_bits_low & 0x3F; 
}

void watch_registers_set_date_year(uint8_t* date_bits_low, uint8_t* date_bits_high, uint8_t year){
    *date_bits_low = (*date_bits_low & 0x80) | (year & 0x7F); // Set the lower 2 bits of LSB
}
void watch_registers_set_date_month(uint8_t* date_bits_low, uint8_t* date_bits_high, uint8_t month){
    *date_bits_high = (*date_bits_high & 0xF8) | ((month >> 1) & 0x07); 
    *date_bits_low = (*date_bits_low & 0x7F) | ((month & 0x01) << 7); 
}
void watch_registers_set_date_day_of_month(uint8_t* date_bits_low, uint8_t* date_bits_high,uint8_t day_of_month){
    *date_bits_high = (*date_bits_high & 0x07) | ((day_of_month & 0x1F) << 3); // Set the upper 5 bits of MSB
}
void watch_registers_get_date(uint8_t date_bits_low, uint8_t date_bits_high, uint8_t* year, uint8_t* month, uint8_t* day_of_month){
    *year = date_bits_low & 0x7F; // Get the lower 7 bits of LSB
    *month = ((date_bits_high & 0x07) << 1) | ((date_bits_low >> 7) & 0x01); // Get the upper 3 bits of MSB and the lower bit of LSB
    *day_of_month = (date_bits_high >> 3) & 0x1F; // Get the upper 5 bits of MSB
}
