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

def get_json_data():
    site_name="Sioux Falls Regional 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.sfairport.com/parking/parking-rates-map"

    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)
    # Get the page source
    time.sleep(2)  # Adjust the sleep time as needed
    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 elements with class 'elementor-element'
    element = soup.find('div',class_='flight-deck')
    if element is None or not element:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

    else:

        lot_divs = element.find_all('div', class_='col-md-3')

        # Initialize a dictionary to store lot and available information
        parking_data = []

        # Iterate over each lot div
        for div in lot_divs:
            # Find the lot name
            if div.find('h3', class_='hdr'):
                lot_name = div.find('h3', class_='hdr').text.strip()
                
                # Find the available spots
                available = div.find_next_siblings()[2].find('p').text.strip()
                
                # Store the lot name and available spots in the dictionary
                parking_data.append({
                    'Title':lot_name,
                    'Available Spots':  available,
                })
                
                existing_location = Locations.objects.filter(fsLocationName=lot_name,fsPartnerId=partnerid).first()
                if existing_location:
                # Update existing record
                    existing_location.fiParkingSlots = available
                    existing_location.save()
                else:
                # Create new record
                    new_parking = Locations(
                                    fsPartnerId=partnerid,
                                    fsLocationName=lot_name,
                                    fiParkingSlots=available,
                                )
                    new_parking.save()


        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
