#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdbool.h>
#include <stdio.h>
#include "timer.h"
#include "keyboard.h"
#include "uart.h"
#include "spi_master.h"

void setup_registers() {
	MCUCR &= ~(1 << 4); // PUD
	MCUCR &= ~(1 << 5);
	MCUCR &= ~(1 << 6);
	MCUCR &= ~(1 << 7);
	DDRD &= 0x0F;
	PORTD |= 0xF0;

	DDRC = 0b111111;
	PORTC = 0b001111;
}

void setup() {
	USART_Init(MYUBRR);
	SPI_MasterInit();
	setup_timer();
	setup_registers();
}

int up_amoumt = 0;
int down_amount = 0;
int diff = 0;
int diff_prev = 0;

int main(void) {
	setup();
	puts("Hello\r\n");
	struct key keys[KEYS_AMOUNT];
	struct calculator calc;
	clearCalc(&calc);
	fill_buttons_names(keys);
	while(1) {
		get_physical_keys(keys);
		get_logical_keys(keys);
		
		for (int i = 0; i < KEYS_AMOUNT; i++) {
			bool up, down;
			get_event(&keys[i], &up, &down);
			if (down)
			{
				//printf("button %d\r\n", keys[i].button);
				handleCalc(&calc, keys[i].button);
				output_on_display(&calc);
				//printf("-----\r\n");
				//printf("%ld\r\n", calc.num1);
				//printf("%ld\r\n", calc.num2);
				//printf("%ld\r\n", calc.result);
				//printf("%d\r\n", calc.operation);
				//printf("%d\r\n", calc.state);
				
			}
		}
	}
}

int puts(const char * __str){
	int len = strlen(__str);
	for(size_t i = 0; i < len; i++){
		while (!(UCSR0A & (1<<UDREn)));
		UDR0 = __str[i];
	}
}

int printf( const char * format, ... )
{
	char buffer[16];
	va_list args;
	va_start (args, format);
	size_t s = vsprintf (buffer,format, args);
	for(size_t i = 0; i < s; i++){
		while (!(UCSR0A & (1<<UDREn)));
		UDR0 = buffer[i];
	}
	va_end (args);
	return s;
}