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

// Exercise P4 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 arbiter.sv.
//
// The arbiter runs from slow_clock.  Keys 0 and 1 are the requests.  The
// LEDs and the rightmost digit are as in lab_top.  The screen shows two
// columns, one per requester: the request lamp on top in orange, the grant
// lamp below it in blue.

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] gnt;
    logic       last;

    arbiter i_arbiter
    (
        .clk  ( slow_clock ),
        .rst  ( reset      ),
        .req  ( key [1:0]  ),
        .gnt  ( gnt        ),
        .last ( last       )
    );

    assign led = { 4'b0, last, 1'b0, gnt };

    always_comb
        case (gnt)
        2'b01:   abcdefgh = 8'b1111_1100;  // 0
        2'b10:   abcdefgh = 8'b0110_0000;  // 1
        default: abcdefgh = 8'b0000_0000;  // no grant
        endcase

    assign digit = 8'b0000_0001;

    //------------------------------------------------------------------------
    // Requester 0 on the left, requester 1 on the right: the request lamp
    // on top, the grant lamp below it.  Bright for 1, dim for 0.

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

        for (int i = 0; i < 2; i ++)
            if (x >= 9' (130 + i * 160) & x < 9' (190 + i * 160))
            begin
                if (y >= 50 & y < 110)
                begin
                    red   = key [i] ? 31 : 6;
                    green = key [i] ? 24 : 5;
                end

                if (y >= 150 & y < 210)
                begin
                    green = gnt [i] ? 40 : 8;
                    blue  = gnt [i] ? 31 : 6;
                end
            end
    end

endmodule
