#include "config.h"

#include <avr/io.h>
#include <stdbool.h>
#include <util/delay.h>
#include <stdio.h>

#include "74C922.h"
#include "DHT22.h"
#include "GDM1602K.h"
#include "LM335.h"

enum DisplayMode {TEMP, AVG};

bool b = false;

int main() {
	_delay_ms(1000); // Boot up time, let components catch up
	lcd_init();
	encoder_init();

	lcd_clear();
	lcd_write_string("Hello, world!");

	int temp, hum;
	char celc_str[30];
	char temp_with_unit[20] = "";
	char hum_str[30];
	float celcius = 0.0;
	float humidity = 0.0;
	char temp_unit = 'C';

	uint8_t button_data;
	char btn_string[30];
	bool btn_just_pressed = false;

	long loops = 0;

	while(1) {
		// If encoder has data available
		if(encoder_available() == true) {
			loops = 0xFFFF;
			if(!btn_just_pressed) {
				btn_just_pressed = true;
				button_data = encoder_read();
				sprintf(btn_string, "Knapp %d", button_data);
				lcd_clear();
				if(button_data == 11) {
					if(temp_unit == 'C') temp_unit = 'F';
					else if(temp_unit == 'F') temp_unit = 'K';
					else if(temp_unit == 'K') temp_unit = 'C';
					loops = 0;
				} 
				if(button_data == 3) {
					sprintf(celc_str, "10h Tmp: %s", temp_with_unit);
					sprintf(hum_str, "10h Hum: %.1f%%", humidity-1);	
					lcd_write_strings(celc_str, hum_str);
				}
			}
		} else {
			btn_just_pressed = false;
		}
		
		if(loops == 0) {
			loops = 0x2FFFF;

			int result = DHT22_Read(&temp, &hum);

			lcd_clear();

			if(result == 0) {
				celcius = ((float)temp)/10.0;
				humidity = ((float) hum)/10.0;
				switch(temp_unit) {
					case 'C':
						sprintf(temp_with_unit, "%.1f %c", celcius, temp_unit);
						break;
					case 'F':
						sprintf(temp_with_unit, "%.1f %c", celcius*9/5+32, temp_unit);
						break;
					case 'K':
						sprintf(temp_with_unit, "%.1f %c", celcius + 273.15, temp_unit);
						break;
				}
				sprintf(celc_str, "Temp: %s", temp_with_unit);
				sprintf(hum_str, "Humidity: %.1f%%", humidity);
				
				lcd_write_strings(celc_str, hum_str);
			}
		}
		loops--;
	}
	lcd_write_string("Exited...");
}