File size: 27,781 Bytes
b7a8716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac51d16
b7a8716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac51d16
b7a8716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac51d16
b7a8716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# Import all libraries that are needed
import gradio as gr
import re
import os
import psycopg2
import time
import uuid
from collections import defaultdict

sql_host = os.getenv('SQL_HOST')
db = os.getenv('DB')
user = os.getenv('USER')
password = os.getenv('PASSWORD')
quiz1 = os.getenv('QUIZ1')
quiz2 = os.getenv('QUIZ2')
quiz3 = os.getenv('QUIZ3')
quiz4 = os.getenv('QUIZ4')
quiz5 = os.getenv('QUIZ5')
quiz6 = os.getenv('QUIZ6')
ro_user = os.getenv('RO_USER')
ro_password = os.getenv('RO_PASSWORD')
email_secret = os.getenv('EMAIL')

# Session management
sessions = defaultdict(lambda: {"timer": 60 * 45, "stop_quiz": True})

# Function to generate a unique user id for that session
def generate_session_id():
    return str(uuid.uuid4())

# Function to format time in MM:SS format  
def format_time(seconds):  
    minutes, seconds = divmod(seconds, 60)  
    return f"{minutes:02}:{seconds:02}"

# Function to start the countdown
def start_countdown(session_id):
    while sessions[session_id]["timer"] >= 0:
        if sessions[session_id]["stop_quiz"]:
            return None
        yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(), gr.update()
        time.sleep(1)
        sessions[session_id]["timer"] -= 1
    yield gr.update(value=format_time(sessions[session_id]["timer"])), gr.update(visible=False), gr.update(visible=True)

# Function to stop the countdown
def stop_countdown(session_id):
    sessions[session_id]["stop_quiz"] = True

# Validation function
def validate_inputs(session_id, first_name, last_name, email):

    # Check if first and last name are present
    if not first_name or not last_name:
        return gr.update(visible=True, value="First name and Last Name are required."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
    
    # Check if email address is valid
    if not re.match(rf"^[^@]+@({email_secret})$", email, re.IGNORECASE):
        return gr.update(visible=True, value="Please enter a valid email address."), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
    
    # If inputs are valid, allow quiz to start and take user to next page
    sessions[session_id]["stop_quiz"] = False
    return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)

# Function to reveal the final page, either when timer runs out or "End Quiz" is clicked
def final_page_reveal():
    return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)

# Function to initialize the database
def initialize_database():

    # Details for connecting to Rockborne database
    conn = psycopg2.connect(
        host=sql_host,
        database=db,
        user=user,
        password=password
    )
    cursor = conn.cursor()
    
    # Create the Quiz table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS Quiz (
        quiz_id SERIAL PRIMARY KEY,
        first_name TEXT,
        last_name TEXT,
        email TEXT
    );
    ''')
    
    # Create the QuizAnswers table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS QuizAnswers (
        quiz_id INTEGER,
        question_number INTEGER,
        answer TEXT,
        FOREIGN KEY (quiz_id) REFERENCES Quiz (quiz_id),
        PRIMARY KEY (quiz_id, question_number)
    );
    ''')
    # Create the employee table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS employee (
        id INT PRIMARY KEY,
        name VARCHAR(75),
        department VARCHAR(2),
        manager_id INT
    );
    ''')

    # Insert data into the employee table
    cursor.executemany('''
    INSERT INTO employee (id, name, department, manager_id)
    VALUES (%s, %s, %s, %s)
    ON CONFLICT (id) DO NOTHING;
    ''', [
        (101, 'John', 'A', None),
        (102, 'Dan', 'A', 101),
        (103, 'James', 'A', 101),
        (104, 'Amy', 'A', 101),
        (105, 'Anne', 'A', 101),
        (106, 'Ron', 'B', 101)
    ])

    # Create the courses table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS courses (
        student VARCHAR(1) PRIMARY KEY,
        class VARCHAR(50)
    );
    ''')

    # Insert data into the courses table
    cursor.executemany('''
    INSERT INTO courses (student, class)
    VALUES (%s, %s)
    ON CONFLICT (student) DO NOTHING;
    ''', [
        ('A', 'Maths'),
        ('B', 'English'),
        ('C', 'Maths'),
        ('D', 'Biology'),
        ('E', 'Maths'),
        ('F', 'Computer'),
        ('G', 'Maths'),
        ('H', 'Maths'),
        ('I', 'Maths')
    ])

    # Create the salesperson table    
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS salesperson (
        sales_id INT PRIMARY KEY,
        name VARCHAR(50),
        salary DECIMAL(10, 2),
        commission_rate DECIMAL(5, 2),
        hire_date DATE
    );
    ''')

    # Insert data into the salesperson table  
    cursor.executemany('''
    INSERT INTO salesperson (sales_id, name, salary, commission_rate, hire_date)
    VALUES (%s, %s, %s, %s, %s)
    ON CONFLICT (sales_id) DO NOTHING;
    ''', [
        (1, 'John', 100000, 6, '2006-04-01'),
        (2, 'Amy', 120000, 5, '2010-05-01'),
        (3, 'Mark', 65000, 12, '2008-12-25'),
        (4, 'Pam', 25000, 25, '2005-01-01'),
        (5, 'Alex', 50000, 10, '2007-02-03')
    ])

    # Create the company table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS company (
        com_id INT PRIMARY KEY,
        name VARCHAR(50),
        city VARCHAR(50)
    );
    ''')

    # Insert data into the company table
    cursor.executemany('''
    INSERT INTO company (com_id, name, city)
    VALUES (%s, %s, %s)
    ON CONFLICT (com_id) DO NOTHING;
    ''', [
        (1, 'RED', 'Boston'),
        (2, 'ORANGE', 'New York'),
        (3, 'YELLOW', 'Boston'),
        (4, 'GREEN', 'Austin')
    ])

    # Create the orders table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS orders (
        order_id INT PRIMARY KEY,
        order_date DATE,
        com_id INT,
        sales_id INT,
        amount DECIMAL(10, 2),
        FOREIGN KEY (sales_id) REFERENCES salesperson(sales_id),
        FOREIGN KEY (com_id) REFERENCES company(com_id)
    );
    ''')

    # Insert data into the orders table
    cursor.executemany('''
    INSERT INTO orders (order_id, order_date, com_id, sales_id, amount)
    VALUES (%s, %s, %s, %s, %s)
    ON CONFLICT (order_id) DO NOTHING;
    ''', [
        (1, '2014-01-01', 3, 4, 100000),
        (2, '2014-02-01', 4, 5, 5000),
        (3, '2014-03-01', 1, 1, 50000),
        (4, '2014-04-01', 1, 4, 25000)
    ])

    # Create the tree table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS tree (
        id INT PRIMARY KEY,
        p_id INT
    );
    ''')

    # Insert data into the tree table
    cursor.executemany('''
    INSERT INTO tree (id, p_id)
    VALUES (%s, %s)
    ON CONFLICT (id) DO NOTHING;
    ''', [
        (1, None),
        (2, 1),
        (3, 1),
        (4, 2),
        (5, 2)
    ])

    # Create the movies table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS movies (
        id INT PRIMARY KEY,
        movie VARCHAR(50),
        description VARCHAR(50),
        rating DECIMAL(3, 1)
    );
    ''')

    # Insert data into the movies table
    cursor.executemany('''
    INSERT INTO movies (id, movie, description, rating)
    VALUES (%s, %s, %s, %s)
    ON CONFLICT (id) DO NOTHING;
    ''', [
        (1, 'War', 'Great 3D', 8.9),
        (2, 'Science', 'Fiction', 8.5),
        (3, 'Irish', 'Boring', 6.2),
        (4, 'Ice song', 'Fantasy', 8.6),
        (5, 'House card', 'Interesting', 9.1)
    ])

    # Create the product table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS product (
        product_key INT PRIMARY KEY
    );
    ''')

    # Insert data into the product table
    cursor.executemany('''
    INSERT INTO product (product_key)
    VALUES (%s)
    ON CONFLICT (product_key) DO NOTHING;
    ''', [
        (5,),
        (6,)
    ])

    # Create the customer table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS customer (
        customer_id INT ,
        product_key INT,
        PRIMARY KEY (customer_id, product_key),
        FOREIGN KEY (product_key) REFERENCES product(product_key)
    );
    ''')

    # Insert data into the customer table
    cursor.executemany('''
    INSERT INTO customer (customer_id, product_key)
    VALUES (%s, %s)
    ON CONFLICT (customer_id, product_key) DO NOTHING;
    ''', [
        (1, 5),
        (2, 6),
        (3, 5),
        (3, 6),
        (1, 6)
    ])
    
    # Create the locations table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS locations (
        postal_code VARCHAR(50) PRIMARY KEY,
        city_name VARCHAR(50),
        location VARCHAR(50)
    );
    ''')

    # Insert data into the locations table
    cursor.executemany('''
    INSERT INTO locations (postal_code, city_name, location)
    VALUES (%s, %s, %s)
    ON CONFLICT (postal_code) DO NOTHING;
    ''', [
        ('900', 'Los Angeles', 'California'),
        ('921', 'San Diego', 'CA'),
        ('691', 'Bakersfield', 'California')
    ])

    # Create the departments table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS departments (
        department_id INT PRIMARY KEY,
        department_name VARCHAR(50),
        location VARCHAR(50)
    );
    ''')

    # Insert data into the departments table
    cursor.executemany('''
    INSERT INTO departments (department_id, department_name, location)
    VALUES (%s, %s, %s)
    ON CONFLICT (department_id) DO NOTHING;
    ''', [
        (101, 'HR', 'California'),
        (102, 'IT', 'NY'),
        (103, 'Finance', 'CA')
    ])

    # Create the employees table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(50),
        department_id INT,
        postal_code INT,
        FOREIGN KEY(department_id) REFERENCES departments(department_id)
    );
    ''')

    # Insert data into the employees table
    cursor.executemany('''
    INSERT INTO employees (employee_id, employee_name, department_id, postal_code)
    VALUES (%s, %s, %s, %s)
    ON CONFLICT (employee_id) DO NOTHING;
    ''', [
        (1, 'Kent', '101', 900),
        (2, 'Taylor', '102', 691),
        (3, 'Rachel', '103', 690),
        (4, 'Sam', '101', 921)
    ])

    
    conn.commit()
    cursor.close()
    conn.close()

# Call the function to initialise the database
initialize_database()

# Function to create a new quiz entry and return the quiz_id
def start_quiz(session_id, first_name, last_name, email):

    # Connect to the database
    conn = psycopg2.connect(
        host=sql_host,
        database=db,
        user=user,
        password=password
    )
    cursor = conn.cursor()

    # If quiz is allowed to start (i.e. details are valid), submit the user details into the database with incrementally increased "quiz_id"
    if not sessions[session_id]["stop_quiz"]:
        cursor.execute('''
            INSERT INTO Quiz (first_name, last_name, email)
            VALUES (%s, %s, %s)
            RETURNING quiz_id
        ''', (first_name, last_name, email))
        quiz_id = cursor.fetchone()[0]
    
    # If quiz is not allowed  to start (i.e. details not valid) don't update anything
    else:
        quiz_id = None
    conn.commit()
    cursor.close()
    conn.close()
    return quiz_id

# Function to save a user's answerto a given question to the database
def save_answer(quiz_id, question_number, answer):

    # Connect to the database
    conn = psycopg2.connect(
        host=sql_host,
        database=db,
        user=user,
        password=password
    )
    cursor = conn.cursor()

    # Insert their answer into the database, updating if one already existed for that question
    cursor.execute('''
        INSERT INTO QuizAnswers (quiz_id, question_number, answer)
        VALUES (%s, %s, %s)
        ON CONFLICT (quiz_id, question_number)
        DO UPDATE SET answer = EXCLUDED.answer
    ''', (quiz_id, question_number, answer))
    conn.commit()
    cursor.close()
    conn.close()

    # Return success message
    return "Answer saved successfully!"

# Function to return question details
def get_questions(question):
    questions = {
                 "Question 1": quiz1, 
                 "Question 2": quiz2, 
                 "Question 3": quiz3, 
                 "Question 4": quiz4, 
                 "Question 5": quiz5, 
                 "Question 6": quiz6
                }
    return questions.get(question, "No details available")

# Define the function to execute SQL queries
def execute_sql(query):
    try:
        # Connect to the database
        conn = psycopg2.connect(
            host=sql_host,
            database=db,
            user=ro_user,
            password=ro_password
        )
        cursor = conn.cursor()
        
        # Ensure the query only accesses the appropriate table
        if "quiz" in query.lower():
            return f"### SQL Output\n\nYou are not allowed to access the table 'quiz'."
        if "quizanswers" in query.lower():
            return f"### SQL Output\n\nYou are not allowed to access the table 'quizanswers'."
        if "insert" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'insert'."
        if "delete" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'delete'."
        if "update" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'update'."
        if "merge" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'merge'."
        if "truncate" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'truncate'."
        if "create" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'create'."
        if "alter" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'alter'."
        if "drop" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'drop'."
        if "rename" in query.lower():
            return f"### SQL Output\n\nYou are not allowed use 'rename'."
        
        cursor.execute(query)
        conn.commit()
        
        # If the query involves a select statement, display their answer in a formatted table
        if "select" in query.strip().lower():
            results = cursor.fetchall()
            column_names = [description[0] for description in cursor.description]
            
            # Create the header row with column names
            header = "| " + " | ".join(column_names) + " |"
            
            # Create the separator row with dashes
            separator = "| " + " | ".join(['---' for _ in column_names]) + " |"
            
            # Create the data rows
            rows = "\n".join(["| " + " | ".join(map(str, row)) + " |" for row in results])
            
            # Combine header, separator, and rows into the final table string
            results_str = f"{header}\n{separator}\n{rows}"
            
            # Return the formatted table to be rendered in gr.Markdown
            return f"### SQL Output\n\n{results_str}"
        
        # If not a select statement, show that query was executed successfully
        else:
            return "Query executed successfully"
        
    # If  there is an error, return error message
    except Exception as e:
        return str(e)
    
    # Close connection to the database
    finally:
        if conn:
            cursor.close()
            conn.close()

#NEWW
def show_confirmation():
    return (gr.update(visible=True),   # Make confirmation message visible
            gr.update(visible=True),   # Make the "Yes, End Quiz" button visible
            gr.update(visible=True),   # Make the "No, I want to continue" button visible
            gr.update(visible=False))  # Hide the original "End Quiz" button

def hide_confirmation():
    return (gr.update(visible=False),  # Hide confirmation message 
            gr.update(visible=False),  # Hide the "Yes, End Quiz" button 
            gr.update(visible=False),  # Hide the "No, I want to continue" button 
            gr.update(visible=True))   # Show the original "End Quiz" button again


# Define the Gradio app layout
with gr.Blocks() as app:

    # This defines the landing page, with instructions and inputs for user details
    with gr.Column(visible=True) as intro:

        # Generate a unique session_id for the user
        session_id = gr.State(generate_session_id)

        # HTML code for welcome page and instructions
        gr.Markdown("<h1 style='text-align: center;'>WELCOME</h1>")
        gr.Markdown("<h2>Instructions</h2>", elem_id="instructions-title")
        gr.Markdown("""
        <p>This test is designed to evaluate your SQL proficiency by measuring your ability to write efficient and accurate SQL select queries. It will help you identify your strengths and areas for improvement.</p>
        <p>This test consists of 6 SQL questions with varied levels of difficulty.</p>
        <p>You will have 45 minutes to complete the assessment.</p>
        <p>To start this test please input your first name, last name and your email address, then click on ‘Begin Test’.</p>
        <p>After starting the test, click ‘Test query’ to test your SQL queries and view its output.</p>
        <p>For each question, you <b>must</b> press 'Save Answer' for the answer to be submitted. These can be resubmitted, but only the most recent version will be marked.</p>
        <p>When the timer reaches 0, the test will immediately end and no further answers can be submitted.</p>
        <p>Clicking "End Quiz" before the time finishes will automatically end the quiz, it does <b>not</b> submit any unsaved answers.</p>
        <p><b style="font-size:20px;">Do NOT refresh the page, this will start a new user entry.</b></p>
        """)

        # Textboxes for users to input details
        first_name = gr.Textbox(label="First Name")
        last_name = gr.Textbox(label="Last Name")
        email = gr.Textbox(label="Email")
        error_message = gr.Markdown("", visible=False)
        submit_button = gr.Button("Start Test")

    # This defines the exit page, telling the user to quit the application
    with gr.Column(visible=False) as exit_page:
        gr.HTML(
            """
            <div style="display: flex; justify-content: center; align-items: flex-start; height: 100vh; margin: 0;">
                <div style="text-align: center; border: 2px solid black; padding: 20px; padding-bottom: 40px; margin-top: 40px;">
                    <h1 style="margin-bottom: 30px;">Exit Page</h1>
                    <p style="margin-bottom: 20px;">Thank you for completing the quiz.</p>
                    <p style="margin-bottom: 20px;">Please do not try to reattempt this assessment, only your first submission will be marked.</p>
                    <p>You may now close this page within your browser.</p>
                </div>
            </div>
            """
        )

    # This defines the page with quiz questions
    with gr.Column(visible=False) as quiz_page:

        # Important instructions repeated in a markdown
        gr.Markdown(
            """
            <div style="display: flex; flex-direction: column; align-items: center;">
                <h1>Quiz Questions</h1>
                <div style="border: 2px solid black; padding: 20px; text-align: left; width: 100%; max-width: 1000px;">
                    <b>Remember the following:</b>
                    <div style="margin-top: 10px;">
                        <ul style="list-style-position: inside; padding-left: 20px;">
                            <li>For each question, you <b>must</b> press 'Save Answer' for the answer to be submitted. These can be resubmitted, but only the most recent version will be marked.</li>
                            <li>When the timer reaches 0, the test will immediately end and no further answers can be submitted.</li>
                            <li>Clicking "End Quiz" before the time finishes will automatically end the quiz; it does <b>not</b> submit any unsaved answers.</li>
                            <li><b style="font-size:20px;">Do NOT refresh the page, this will start a new user entry.</b></p></li>
                    </div>
                </div>
            </div>
            """
        )

        quiz_id = gr.State(value=None)  # State to store the quiz_id

        # First row on this page
        with gr.Row():
            # Fixed left pane with questions and timer box
            with gr.Column(scale=1, min_width=200):
                # Create buttons for each question
                question_buttons = [
                    gr.Button(value=f"Question {i}", elem_id=f"question_{i}") for i in range(1, 7)
                ]

                # Timer box
                text = gr.Textbox(label="Remaining time", value="45:00", lines=1, interactive=False)
            
            # Right pane with details and SQL editor
            with gr.Column(scale=3):

                # Shows active question number at the top of the page
                details_output = gr.Markdown(value="")
                
                # Editor for user to put their code in
                sql_editors = [gr.Code(label=f"Write your answer for Question {i} here:", language="sql", lines=8, visible=False) for i in range(1, 7)]
                
                # Output to show the result of user's query when they test it
                sql_output = gr.Markdown("""<h3>SQL Output</h3><br><br>""")
                
                question_number = gr.State(value=None)

                # Function to allow users to click between questions
                def on_question_click(question_number):
                    question_number = int(question_number)
                    question = f"Question {question_number}"
                    editor_updates = [gr.update(visible=(i == question_number)) for i in range(1, 7)]
                    # Clear the SQL output
                    sql_output_update = gr.update(value="")
                    return [get_questions(question), question_number] + editor_updates + [sql_output_update]
                
                # Bund the function 'on_question_click' to the question buttons
                for i in range(1, 7):
                    question_buttons[i-1].click(
                        on_question_click,
                        inputs=[gr.Number(value=i, visible=False)],
                        outputs=[details_output, question_number] + sql_editors + [sql_output],
                        concurrency_limit=20
                    )
                # Row with buttons to test query, save answer and end quiz
                with gr.Row():
                    with gr.Column(scale=1):
                        test_query_button = gr.Button("Test Query")
                    with gr.Column(scale=1):
                        save_answer_button = gr.Button("Save Answer")
                    with gr.Column(scale=1):
                        end_quiz_button = gr.Button("End Quiz")
                
                # Function to test a user's query
                def test_query(active_question, *sql_codes):
                    if active_question is not None:
                        # Convert active_question to an integer
                        question_index = int(active_question) - 1
                        sql_code = sql_codes[question_index]
                        return execute_sql(sql_code)
                    return "Please select a question first."
                
                # Function to save a user's query
                def save_answer_multi(quiz_id, active_question, *sql_codes):
                    if active_question is not None:
                        # Convert active_question to an integer
                        question_index = int(active_question) - 1
                        sql_code = sql_codes[question_index]
                        return save_answer(quiz_id, int(active_question), sql_code)
                    return "Please select a question first."

                # Bind the test_query_button to the function that tests the query
                test_query_button.click(
                    test_query, 
                    inputs=[question_number] + sql_editors, 
                    outputs=sql_output,
                    concurrency_limit=20
                )

                # Bind the save_answer_button to the function that saves the answer
                save_answer_button.click(
                    save_answer_multi, 
                    inputs=[quiz_id, question_number] + sql_editors, 
                    outputs=sql_output,
                    concurrency_limit=20
                )

                # Confirmation components
                confirmation_message = gr.Markdown("<b>Are you sure you want to end the quiz?</b>", visible=False)
                with gr.Row():
                    with gr.Column():
                         confirm_button = gr.Button("Yes, end quiz", visible=False)
                    with gr.Column():
                         cancel_button = gr.Button("No, I want to continue", visible=False)

                # Bind the end_quiz_button to show the confirmation popup
                end_quiz_button.click(fn=show_confirmation,
                                    inputs=[],
                                    outputs=[confirmation_message, confirm_button, cancel_button, end_quiz_button]
                )

                # Bind the confirm_button to the functions that end the quiz
                confirm_button.click(fn=final_page_reveal,
                                    inputs=[],
                                    outputs=[error_message, quiz_page, exit_page],
                                    concurrency_limit=20
                )

                # Bind the confirm_button to the function that stops the countdown
                confirm_button.click(fn=stop_countdown,
                                    inputs=[session_id],
                                    outputs=[],
                                    concurrency_limit=20
                )

                # Bind the cancel_button to hide the confirmation popup and show the end quiz button again
                cancel_button.click(fn=hide_confirmation,
                                    inputs=[],
                                    outputs=[confirmation_message, confirm_button, cancel_button, end_quiz_button])



    # Bind the submit_button to functions that validate the inputs and starts the quiz
    submit_button.click(
        fn=lambda sid, fn, ln, em: (
            validate_inputs(sid, fn, ln, em)[0],
            validate_inputs(sid, fn, ln, em)[1],
            validate_inputs(sid, fn, ln, em)[2],
            start_quiz(sid, fn, ln, em)
        ),
        inputs=[session_id, first_name, last_name, email],
        outputs=[error_message, intro, quiz_page, quiz_id],
        concurrency_limit=20
    )

    # Also bind the submit_button to the function that starts the countdown
    submit_button.click(
        fn=start_countdown,
        inputs=[session_id],
        outputs=[text, quiz_page, exit_page],
        concurrency_limit=20
    )

    # Also bind the submit_button to the function to reveal question 1 on the new page
    submit_button.click(
        fn=on_question_click,
        inputs=[gr.Number(value=1, visible=False)],
        outputs=[details_output, question_number] + sql_editors + [sql_output],
        concurrency_limit=20
    )

# Launch the app with support for concurrent users
if __name__ == "__main__":
    app.launch(share=False, max_threads=40)  # Adjust max_threads as needed