import json

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from models.models import Locations,Partners
from notify import send_email

def get_json_data():
    site_name="San Francisco Bay Oakland 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.oaklandairport.com/services-amenities/parking/"
    
    # Configure Selenium WebDriver
    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
    page_source = driver.page_source
    driver.quit()  # Make sure to close the driver after use
    
    # Parse the page source with BeautifulSoup
    soup = BeautifulSoup(page_source, 'html.parser')

    # Find all divs containing parking information
    parking_divs = soup.find_all("div", class_="parking-data-text")
    if parking_divs is None or not parking_divs:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:

        # Initialize list to store data
        parking_data = []
        
        # Extract data from each parking div
        for text_div, percent_div in zip(parking_divs, soup.find_all("div", class_="parking-data-percent")):
            try:
                description = text_div.find('div', class_='parking-description').get_text(strip=True).split('$')[0]
                available_number = text_div.find('div', class_='parking-available-number').get_text(strip=True)
                
                # Extract percentage full
                percent_text = percent_div.find('span', class_='percent-text').get_text(strip=True)
                percent_full = percent_text.replace('% full', '').strip()
                
                # Store data in dictionary
                parking_data.append({
                    'description': description,
                    'available_number': available_number,
                    'percent_full': percent_text
                })
                # Check if location already exists in the database
                existing_location = Locations.objects.filter(fsLocationName=description,fsPartnerId=partnerid).first()
                if existing_location:
                        # Update existing record
                        existing_location.fiParkingSlots = available_number+ " Available"
                        existing_location.fsoccupied_spots=percent_text
                        existing_location.save()
                else:
                        # Create new record
                    new_parking = Locations(
                                            fsPartnerId=partnerid,
                                            fsLocationName=description,
                                            fiParkingSlots=available_number + " Available",
                                            fsoccupied_spots=percent_text
                                        )
                    new_parking.save()
            except AttributeError:
                # Skip this div if it doesn't contain the expected elements
                continue

    # Convert the list of dictionaries to JSON
    json_data = json.dumps(parking_data)
    return json_data
