LIBRARY ieee;
USE ieee.numeric_std.all;
USE ieee.std_logic_1164.all;

ENTITY sci_parser IS
	PORT 
	(
		CLK				:	IN std_logic;								--! interni hodinovy signal
		RST				:	IN std_logic;								--! signal reset aktivni v log. 1
		
		SCLK			:	IN std_logic;								--! Hodinovy signal SPI
		CS_N			:	IN std_logic;								--! Chip select signal SPI
		MOSI			:	IN std_logic;								--! Master Out Slave In SPI 
		MISO			:	OUT std_logic;								--! Master In Slave Out SPI	
		
		SCI_add			:	OUT std_logic_vector(7 DOWNTO 0);			--! cislo linky SCI
		SCI_val			:	OUT std_logic_vector(7 DOWNTO 0);			--! data odesilane po SCI
		SCI_vld			:	OUT std_logic								--! Nove prijata data jsou validni
	);
END sci_parser;

ARCHITECTURE Behavioral OF sci_parser IS

	-- spi
	SIGNAL DOUT 				:	std_logic_vector(15 DOWNTO 0)	:= (OTHERS => '0');
	SIGNAL DOUT_VLD				:	std_logic						:= '0';
	SIGNAL DOUT_VLD_prev		:	std_logic						:= '0';
	SIGNAL DOUT_VLD_redge		:	std_logic						:= '0';
	SIGNAL DOUT_ERR				:	std_logic						:= '0';

	SIGNAL iDATA 				:	std_logic_vector(15 DOWNTO 0)	:= (OTHERS => '0');

	TYPE 	t_State 			IS (Recieve, Valid);
	SIGNAL	State				:	t_State	  := Recieve;

BEGIN

	spi_slave: ENTITY work.spi_slave
	GENERIC MAP
	(
		BYTES		=>	2
	)

	PORT MAP
	(
		CLK			=> CLK,
		RST			=> RST,
		SCLK		=> SCLK,
		CS_N 		=> CS_N,
		MOSI		=> MOSI,
		MISO		=> MISO,
		DIN			=> x"0000",
		DOUT		=> DOUT,
		DOUT_VLD	=> DOUT_VLD,
		DOUT_ERR	=> DOUT_ERR
	);
	

	PROCESS (CLK)
	BEGIN
		IF (rising_edge(CLK)) THEN
			DOUT_VLD_prev <= DOUT_VLD;
		END IF;
	END PROCESS;

	DOUT_VLD_redge <= DOUT_VLD AND NOT DOUT_VLD_prev;

	PROCESS (CLK)
	BEGIN
		IF rising_edge(CLK) THEN
			IF (RST = '1') THEN
				State <= Recieve;
				SCI_vld <= '0';
			ELSE
				CASE State IS
					-- cekani na prijeti datoveho ramce
					WHEN Recieve =>
					SCI_vld <= '0';
						IF (DOUT_VLD_redge = '1') THEN
							SCI_add <= DOUT(15 DOWNTO 8);
							SCI_val <= DOUT(7 DOWNTO 0);
							State <= Valid; -- pokud se jedna o zapis
						END IF;

					-- vysle impuls, ze data jsou validni
					WHEN Valid =>
						SCI_vld <= '1';
						State <= Recieve;	
				END CASE;
			END IF;
		END IF;
	END PROCESS;

END Behavioral;