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

// Exercise P6 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 code_lock.sv.
//
// The lock runs from slow_clock.  Any key is the code button: hold it or
// release it through a tick of slow_clock to enter 1, 0, 1.  The LEDs and
// the rightmost digit are as in lab_top.  The screen shows a lock: a red
// square while it is closed, a green one when it is open, with the three
// small lamps A, S1, S0 above it.

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       a, open;
    logic [1:0] state;

    code_lock i_code_lock
    (
        .clk   ( slow_clock ),
        .rst   ( reset      ),
        .btn   ( | key      ),
        .a     ( a          ),
        .state ( state      ),
        .open  ( open       )
    );

    assign led = { 4'b0, open, state, a };

    // The number of the state: how many digits of the code are matched

    always_comb
        case (state)
        2'd0: abcdefgh = 8'b1111_1100;  // 0
        2'd1: abcdefgh = 8'b0110_0000;  // 1
        2'd2: abcdefgh = 8'b1101_1010;  // 2
        2'd3: abcdefgh = 8'b1111_0011;  // 3 and the dot: open
        endcase

    assign digit = 8'b0000_0001;

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

    wire [2:0] lamp = { a, state [1], state [0] };

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

        for (int i = 0; i < 3; i ++)
            if (x >= 9' (170 + i * 50) & x < 9' (200 + i * 50) & y >= 40 & y < 70)
            begin
                green = lamp [2 - i] ? 40 : 8;
                blue  = lamp [2 - i] ? 31 : 6;
            end

        if (x >= 180 & x < 300 & y >= 100 & y < 220)
        begin
            if (open)
                green = 63;
            else
                red   = 31;
        end
    end

endmodule
