from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.utils import timezone
import time

import mysql.connector

def Index(request):
    return render(request, "AJAX/index.html")

def connectToMyDB():
    return mysql.connector.connect(
        host="localhost",
        user="Student",
        passwd="P@$$w0rd",
        database="myDB"
    )

def Countries(request):
    try:
        db = connectToMyDB()
        cursor = db.cursor()
        cursor.execute("SELECT name FROM Country")
        countries = cursor.fetchall()
        html = ""
        for country in countries:
            html += f"<option>{country[0]}</option>"
        if html != "":
            html = f"""
    <select id='Country' name='Country' onchange='loadStates()'>
    <option>--Select Country--</option>{html}</select>"""
        return HttpResponse(html)
    except:
        return HttpResponse("")

def States(request):
    countryName = str(request.GET.get('countryName', ""))
    useLocalName = str(request.GET.get('useLocalName', "no"))=="yes"
    try:
        db = connectToMyDB()
        cursor = db.cursor()
        sql = f"""
           SELECT s.Name, s.LocalName FROM State s 
           JOIN Country c ON s.Country=c.Code 
           WHERE c.Name = '{countryName}'"""
        cursor.execute(sql)
        result = cursor.fetchall()
        html = ""
        for rec in result:
            html += f"<option>{rec[useLocalName]}</option>"
        if html != "":
            html = f"<select>{html}</select>"
        return HttpResponse(html)
    except:
        return HttpResponse("")

def CheckUser(request):
    userName = str(request.GET.get('userName', ""))
    try:
        db = connectToMyDB()
        cursor = db.cursor()
        sql = f"SELECT Name FROM Member WHERE Name='{userName}'"
        cursor.execute(sql)
        result = cursor.fetchone()
        time.sleep(5)       # Simulate latency for 5 seconds
        for rec in result:
            return HttpResponse(rec)
        return HttpResponse("")
    except:
        return HttpResponse("")

def isLeapYear(year:int)->bool:
    if ((year % 4) != 0): return False
    if ((year % 100) != 0): return True
    if ((year % 400) != 0): return False
    return True

def GetDays(request):
    year = int(request.GET.get('year', timezone.now().year))
    sMonth = str(request.GET.get('sMonth', ""))

    nDays = {
        "JAN": 31,
        "FEB": (28,29)[isLeapYear(year)],
        "MAR": 31,
        "APR": 30,
        "MAY": 31,
        "JUN": 30,
        "JUL": 31,
        "AUG": 31,
        "SEP": 30,
        "OCT": 31,
        "NOV": 30,
        "DEC": 31,
    }
    result = "<select id='Days' name='Days'>"
    for d in range(1, nDays[sMonth] + 1):
        result += f"<option>{d}</option>"
    return HttpResponse(f"{result}</select>")


