library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

use work.utils_pkg.all; --  Imports the standard textio package.

package spi_types is
	
	-- Constants
	constant XFER_MAX_SIZE_BITS	: natural := 32;
	constant SIZEOF_CMD			: natural := 2*XFER_MAX_SIZE_BITS;
	
	-- Types
	type cmd_t is record
		xfer_size	: unsigned(XFER_MAX_SIZE_BITS-1 downto 0);
		data_size	: unsigned(XFER_MAX_SIZE_BITS-1 downto 0);
	end record;	

	type ctrl_t is record
		cpol		: std_logic;
		cpha		: std_logic;
		msb_first	: std_logic;
		clk_div		: unsigned(7 downto 0);
	end record;	
	
	type status_t is record
		cmd_fifo_full		: std_logic;
		cmd_fifo_empty		: std_logic;
		write_fifo_full		: std_logic;
		write_fifo_empty	: std_logic;
		read_fifo_full		: std_logic;
		read_fifo_empty		: std_logic;
		xfer_busy			: std_logic;
	end record;	

	-- Functions
	function to_cmd (xfer_size, data_size : natural) return cmd_t;
	function to_unsigned (cmd : cmd_t) return unsigned;
	function to_cmd (cmd : unsigned) return cmd_t;
	
end spi_types;

package body spi_types is

	function to_cmd(xfer_size, data_size : natural) return cmd_t is
	variable res : cmd_t;
	begin
		res.xfer_size := to_unsigned(xfer_size, res.xfer_size'length);
		res.data_size := to_unsigned(data_size, res.data_size'length);
		return res;
	end to_cmd;	
	
	function to_unsigned(cmd : cmd_t) return unsigned is
	variable res : unsigned(SIZEOF_CMD-1 downto 0) := (others => '0');
	begin
		res(res'left downto res'left - cmd.xfer_size'length+1) := cmd.xfer_size;
		res(res'left - cmd.xfer_size'length downto res'left - cmd.xfer_size'length - cmd.data_size'length +1) := cmd.data_size;
		return res;
	end to_unsigned;	

	function to_cmd (cmd : unsigned) return cmd_t is
	variable res : cmd_t;
	begin
		res.xfer_size := cmd(cmd'left downto cmd'left - res.xfer_size'length+1);
		res.data_size := cmd(cmd'left - res.xfer_size'length downto 0);
		
		return res;
	end to_cmd;	

end spi_types;
