#include "spi_proto.h"
#include "spi.h"

/***** MASTER *****/

uint8_t mst_buf[5];

uint16_t spi_master_transceive(uint8_t opcode, uint8_t addr, uint16_t value)
{
//	for(uint8_t j=0; j<10; ++j){
		mst_buf[0] = opcode;
		mst_buf[1] = addr;
		mst_buf[2] = value >> 8;
		mst_buf[3] = value & 0xff;
		mst_buf[4] = 0; // additional 0 to read the last byte from the slave
		spi_mst_start_packet();
		spi_mst_write_read(5,mst_buf);
		spi_mst_end_packet();
		for(uint8_t i=0; i<5; ++i){
			mst_buf[0] = 0;
			mst_buf[1] = 0;
			mst_buf[2] = 0;
			mst_buf[3] = 0;
			mst_buf[4] = 0;
			spi_mst_start_packet();
			spi_mst_write_read(5,mst_buf);
			spi_mst_end_packet();
			// bytes from slave are received shifted right by one
			if(mst_buf[1] == opcode && mst_buf[2] == addr){ // valid answer
				return ((mst_buf[3] << 8) | mst_buf[4]);
			}
		}
//	}
	return 0xffff; // error-code
}


uint16_t read_temperature(uint8_t number)
{
	return 0;
}

uint8_t read_var8(uint8_t number)
{
	return 0;
}

uint16_t read_var16(uint8_t number)
{
	return 0;
}

void write_var8(uint8_t number, uint8_t value)
{
}

void write_var16(uint8_t number, uint16_t value)
{
}

void call_func(uint8_t number)
{
}


/***** MASTER END *****/
/***** SLAVE *****/


uint16_t spi_proto_slaveaction(uint8_t opcode, uint8_t addr, uint16_t data) {
	uint16_t retval = 0;
	switch(opcode){
		case 1:
			retval = data;
			break;
		case 2:
			retval = (*spi_proto_globals8[addr]);
			break;
		case 3:
			retval = (*spi_proto_globals16[addr]);
			break;
		case 4:
			(*spi_proto_globals8[addr]) = data;
			break;
		case 5:
			(*spi_proto_globals16[addr]) = data;
			break;
		case 6:
			(*spi_proto_funcs[addr])();
			//TODO: prevent a function from being run several times because the message gets repeated.
			break;
		case 7:
			//TODO
			retval = 0;
			break;
		default:
			break;
	}
	return retval;
}

/***** SLAVE END *****/
