import json
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from models.models import Locations,Partners
from notify import send_email
key_obj={
     "t1":'Terminal 1',
     "t2":'Terminal 2',
     "lotA":'Lot A',
     "lotB":'Lot B',
     "lotC":'Lot C',
     "lotD":'Lot D',
     "lotE":'Lot E',
}
def get_json_data():
    site_name="St. Louis Lambert International Airport"
    partners=Partners.objects(fsBusinessName=site_name)

    if not partners:
        json_data = {'message': 'No partners found'}
        return json_data
    
    for partner in partners:
        locations=Locations.objects(fsPartnerId=partner.id)
        partnerid=str(partner.id)
        
    # URL of the webpage to scrape
    url = "https://www.flystl.com/parking-and-transport/parking"

    options = Options()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    
    # Load the webpage
    driver.get(url)
    time.sleep(2)  # Adjust the sleep time as needed
    # Get the page source
    page_source = driver.page_source
    # Extract the HTML content
    html = page_source
    # Extract the HTML content
    # Parse the HTML
    # Parse the HTML
    soup = BeautifulSoup(html, 'html.parser')

    # Find all parent divs containing parking information
    parent_divs = soup.find('div',class_="lots")
    if parent_divs is None or not parent_divs:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

    else:
        child_divs = parent_divs.find_all('div',class_="park")
        # Initialize list to store data
        parking_data = []

        # Extract title, spaces, and type
        for row in child_divs:
            title = row.find("span")['class'][0]
            space = row.find("span").text.strip()
            
            parking_data.append({
                'Title': title,
                'Available Spots': space,
            })
            # Check if location already exists in the database
            existing_location = Locations.objects.filter(fsLocationName=key_obj[title],fsPartnerId=partnerid).first()
            if existing_location:
                    # Update existing record
                existing_location.fiParkingSlots = space
                existing_location.save()
                existing_location.fsLocationName = key_obj[title]
                existing_location.save()
            else:
                    # Create new record
                new_parking = Locations(
                            fsPartnerId=partnerid,
                            fsLocationName=key_obj[title],
                            fiParkingSlots=space,
                        )
                new_parking.save() 

                

        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
