import smtplib
import winsound
import requests
import time
import json
import datetime
import os

def beeper():
    while True:
        winsound.Beep(2500, 1000)
        time.sleep(0.5)


date = str(input("Please enter desired slot date (dd-mm-yyyy) eg. 01-12-2020: \nDefault date (today's date):"))
if(len(date) == 0):
    date = datetime.datetime.now().strftime("%d-%m-%Y")


pincode = ''

while(len(pincode) == 0):
    pincode = str(input("Please area pincode: \n"))

minAgeLimit = input("Please enter an age group (Either 18 or 45): \nDefault value (45):")
if(len(minAgeLimit) == 0):
    minAgeLimit = 45

# email = input("Please enter an email address if required to be notified through an email: ")
waitSeconds = input("Please enter the time to be refreshed(in seconds):\nDefault value (30 sec):")
if(len(waitSeconds) == 0):
    waitSeconds = 30

flag = 0

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}

try:

    # Find State
    defState = False
    while defState:
        uri = "https://cdn-api.co-vin.in/api/v2/admin/location/states"
        states = requests.request("GET", uri, headers=headers).json()

        print('State Code:   | State Name' )

        # stateDictionary = {}

        for state in states["states"]:
            # print(state["state_id"] + ' : ' + state["state_name"])
            # stateDictionary[state['state_name']] = state['state_id']
            print(str(state['state_id']) + ' : ' + str(state['state_name']))

        stateId = input("Please enter state code\n")

        if(stateId.isnumeric()):
            flag = 1
            break
        else:
            print('Try again')
            break

        if(flag!=0):
            break

        
        # Find District
        
    while defState:
        print('District Code:   | District Name' )
        uri = "https://cdn-api.co-vin.in/api/v2/admin/location/districts/{stateId}".format(stateId=stateId)
        districts = requests.request("GET", uri, headers = headers).json()
        # print(districts)
        for district in districts["districts"]:
            print(str(district['district_id']) + ' : ' + str(district['district_name']))

        districtId = input("Please enter District code\n")

            
        if(districtId.isnumeric()):
            flag = 1
            break
        else:
            print('Try again')
            break
                        
        
        if(flag!=1):
            break
    # Find slots


    while True:

        currentTime = datetime.datetime.now()
        # uri = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id={districtId}&date={date}".format(districtId=districtId,date=date)

        uri = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={pincode}&date={date}".format(pincode=pincode,date=date)

        centers = requests.request("GET", uri, headers=headers).json()

        # print(centers)
        # print('\n\n\n')
     

        if(len(centers) > 0):
            for center in centers['centers']:
                for session in center['sessions']:
                    if(session["min_age_limit"] == minAgeLimit):
                        print('Centre Name: ' + center['name'] + ' | ' + center['address'])
                        print("Fees: ",center["fee_type"],"Age Group: ",session["min_age_limit"]) 
                        
                        print("Slot available: ",session["available_capacity"]," | Vaccine: ",session["vaccine"],"\n")
                        
                        if(session["available_capacity"] > 0):
                            print("-------------------- VACCINE SLOT AVAILABLE -----------------------")
                            print("-------------------- Press Ctrl + C (twice) to stop -----------------------")
                            beeper()
                            time.sleep(60)

                        print("Timings: \n")
                        for slot in session["slots"]:
                            print("    " + slot + '\n')            
        else:
            print("No centers available.")
        

        # else:
        #     winsound.Beep(3000, 500)
        #     if len(email)>0:
        #         senders_mail = 'xxxxx@gmail.com'
        #         receivers_mail=email
        #         message = 'Subject: {SUBJECT}\n\n{TEXT}'.format(SUBJECT='Cowin Center found', TEXT=json.dumps(webData["sessions"], indent = 3))
        #         mail = smtplib.SMTP('smtp.gmail.com',587)
        #         mail.ehlo()
        #         mail.starttls()
        #         mail.login('username','password')
        #         mail.sendmail(senders_mail,receivers_mail,message)
        #         mail.close()
            

        # print("LastRefresh: {currentTime}, Age Group: {minAgeLimit} Years, Next Refresh In: {waitSeconds} Seconds".format(currentTime=currentTime,minAgeLimit=minAgeLimit,waitSeconds=waitSeconds))
        print("-------------------- Press Ctrl + C (twice) to stop -----------------------")
        
        time.sleep(int(waitSeconds))
        # if flag!=2:
        #     break


except:
    print("An Error Occurred.")


     