`timescale 1ns/1ns

module tb
(
    input   wire    clk,
    input   wire    nreset,
    input   wire    key,
    input   wire    key2,
    output  wire    [31:0] rdata_wire 
); 

localparam x_address = 9'h7FF;
localparam y_address = 6'h3F;

reg key1_temp1,key1_temp2;
reg key2_temp1,key2_temp2;

always @(posedge clk or negedge nreset)
begin
    if(~nreset)
    begin
        key1_temp1 <= 1'b0;
        key1_temp2 <= 1'b0;

        key2_temp1 <= 1'b0;
        key2_temp2 <= 1'b0;
    end
    else
    begin
        key1_temp1 <= key;
        key1_temp2 <= key1_temp1;

        key2_temp1 <= key2;
        key2_temp2 <= key2_temp1;
    end
end

wire key_write = ~key1_temp1 & key1_temp2;
wire key_read = ~key2_temp1 & key2_temp2;

reg [4:0] i;
//Test State machine
reg [31:0] wdata;
reg w_r_signal_i;
reg [8:0] wxaddr;
reg [5:0] wyaddr;
reg Start_signal_i;
wire Done_signal_o;
wire [31:0] rdata;
reg  [31:0] rdata_reg;
reg  erase_reg;

assign rdata_wire = rdata_reg;

always @(posedge clk or negedge nreset)
begin
	if(~nreset)
	begin
		i <= 5'd0;
		wdata <= 32'd0;
		w_r_signal_i <= 1'b0;
		wxaddr <= x_address;
		wyaddr <= y_address;
		Start_signal_i <= 1'b0;
	end
	else
	begin
		case (i)
		5'd0:	
			begin
                if(key_write)
                begin
                    Start_signal_i <= 1'b1;
                    erase_reg <= 1'b1;
                    i <= i + 1'b1;
                end
                else if(key_read)
                begin
                    i <= 5'd6;
                end
			end
		5'd1:
			begin
				Start_signal_i <= 1'b0;
				erase_reg <= 1'b0;
				i <= i + 1'b1;
			end
		5'd2:
			begin
				if(Done_signal_o)
				begin
					i <= i + 1'b1;
				end
			end
		5'd3:
			begin
				wdata <= 32'hFFFBCCDD;//wdata + 1'b1;
				wxaddr <= x_address;//wxaddr + 1'b1;
				wyaddr <= y_address;//wyaddr + 1'b1;
				w_r_signal_i <= 1'b1; //Write To Flash
				Start_signal_i <= 1'b1;//Start_to Write
				i <= i + 1'b1;
			end
		5'd4:
			begin
			    w_r_signal_i <= 1'b0;
				Start_signal_i <= 1'b0;
				i <= i + 1'b1;
			end
			
		5'd5:
			begin
				if(Done_signal_o) 
				i <= 5'd0;
			end


		5'd6:
			begin
			
				wxaddr <= x_address;
				wyaddr <= y_address;
			
				i <= i + 1'b1;
			end
		5'd7:
			begin
				w_r_signal_i <= 1'b0;		//Read Signal
				Start_signal_i <= 1'b1;	
				i <= i + 1'b1;
			end
			
		5'd8:
			begin
			    w_r_signal_i <= 1'b0;
				Start_signal_i <= 1'b0;
				i <= i + 1'b1;
			end
			
		5'd9:
			begin
				if(Done_signal_o) 
				i <= i + 1'b1;
			end
			
		5'd10:
			begin
				rdata_reg<=rdata;
				i <=5'd0;
			end
		endcase
	end
end

Gowin_Flash_Controller_Top Gowin_Flash_Controller_template 
(
    .clk_i(clk),
	.nrst_i(nreset), 
	.wdata_i(wdata),
	.wr_en_i(w_r_signal_i),
	.wxaddr_i(wxaddr),
	.wyaddr_i(wyaddr),
	.done_flag_o(Done_signal_o),
	.start_flag_i(Start_signal_i),
	.rdata_o(rdata),
	.erase_en_i(erase_reg)
);

endmodule