// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon
// This module uses few parameterization and relaxed typing rules

// Exercise P5 in the hackathon setup of Basics-Graphics-Music (BGM):
// https://github.com/yuri-panchul/basics-graphics-music
//
// Copy a directory such as hackathon/problems/3_d_flip_flop, replace its
// hackathon_top.sv with this file and add snail_fsm.sv.
//
// The FSM runs from slow_clock.  Any key is the input A: hold it or release
// it through a tick of slow_clock.  The LEDs and the rightmost digit are as
// in lab_top.  The screen shows three lamps: A in blue, S0 in orange and
// S1 = Y in green.

module hackathon_top
(
    input  logic       clock,
    input  logic       slow_clock,
    input  logic       reset,

    input  logic [7:0] key,
    output logic [7:0] led,

    // A dynamic seven-segment display

    output logic [7:0] abcdefgh,
    output logic [7:0] digit,

    // LCD screen interface

    input  logic [8:0] x,
    input  logic [8:0] y,

    output logic [4:0] red,
    output logic [5:0] green,
    output logic [4:0] blue,

    inout  logic [3:0] gpio
);

    //------------------------------------------------------------------------

    logic [1:0] state;

    wire a = | key;

    snail_fsm i_snail_fsm
    (
        .clk   ( slow_clock ),
        .rst   ( reset      ),
        .a     ( a          ),
        .state ( state      )
    );

    assign led = { 5'b0, state, a };

    always_comb
        case (state)
        2'b00:   abcdefgh = 8'b1111_1100;  // 0
        2'b01:   abcdefgh = 8'b0110_0000;  // 1
        2'b10:   abcdefgh = 8'b1101_1011;  // 2 and the dot: Y = 1
        default: abcdefgh = 8'b0000_0010;  // never reached: a dash
        endcase

    assign digit = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Three square lamps on the 480 x 272 screen: A, S0, S1 = Y.
    // Bright for 1, dim for 0.

    always_comb
    begin
        red   = 0;
        green = 0;
        blue  = 0;

        if (y >= 106 & y < 166)
        begin
            if (x >= 90 & x < 150)
                blue  = a ? 31 : 6;

            if (x >= 210 & x < 270)
            begin
                red   = state [0] ? 31 : 6;
                green = state [0] ? 24 : 5;
            end

            if (x >= 330 & x < 390)
                green = state [1] ? 63 : 12;
        end
    end

endmodule
