import string

codes = []
prefix = 'Key_'
char = lambda x: "'{}'".format(x)

alpha_raw = list(zip([
    0x1E, 0x30, 0x2e, 0x20, 0x12, 0x21, 0x22, 0x23,
    0x17, 0x24, 0x25, 0x26, 0x32, 0x31, 0x18, 0x19,
    0x10, 0x13, 0x1F, 0x14, 0x16, 0x2f, 0x11, 0x2d,
    0x15, 0x2c],
    string.ascii_uppercase))
codes.extend(list(map(lambda x: (x[0], x[1], char(x[1])), alpha_raw)))

digits_raw = list(zip([
    0xb, 0x02, 0x03, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa],
    string.digits))
codes.extend(list(map(lambda x: (x[0], x[1], char(x[1])), digits_raw)))

control_raw = [
    (0x1, 'Escape'),
    (0x2a, 'Left_Shift'),
    (0x36, 'Right_Shift'),
    (0x0E, 'Backspace'),
    (0x38, 'Left_Alt'),
    (0x1d, 'Left_Control'),
]
codes.extend(list(map(lambda x: (x[0], x[1], 0), control_raw)))

codes.append((0x1c, 'Enter', char('\\n')))
codes.append((0x39, 'Space', char(' ')))

table = [0] * 256

with open('kernel/platform/ps2_scan_codes.zig', 'w') as f:
    print('''// Generated by scripts/scan_codes.py
pub export const PS2_Scan_Code = extern enum {
    Key_Invalid = 0x0,''', file=f)
    for i in codes:
        types = [
            (i[0], prefix + i[1] + "_Pressed", 0),
            (i[0] | 128, prefix + i[1] + "_Released", i[2])
        ]
        for code, name, char in types:
            print('    {0} = 0x{1:02x},'.format(name, code), file=f)
            table[code] = char
    print('};', file=f)
    print('const ps2_scan_code_map = [_]u8 {', file=f)
    print(',\n'.join(map(lambda x: '    ' + str(x), table)), file=f)
    print('};', file=f)
    print('pub export fn ps2_scan_code_to_char(scan_code: PS2_Scan_Code) u8 {', file=f)
    print('    const value: usize = @intCast(usize, @enumToInt(scan_code));', file=f)
    print('    return if (value >= ps2_scan_code_map.len) 0 else ps2_scan_code_map[value];', file=f)
    print('}', file=f)
