from selenium import webdriver
from bs4 import BeautifulSoup
import json
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():
    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)
    site_name="San Jose Mineta 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.flysanjose.com/parking/"
    
    # Load the webpage
    driver.get(url)
    
    # Get the page source
    page_source = driver.page_source

    # Parse the HTML content
    soup = BeautifulSoup(page_source, 'html.parser')

    # Find all parking nodes with class="parking-col"
    parking_data = []
    parking_nodes = soup.find_all('div', class_='parking-col')
    if parking_nodes is None or not parking_nodes:
        send_email(site_name)
        json_data ={'message': 'Data not received'}
        return json_data

            
    else:

        # Loop through each parking node
        for node in parking_nodes:
            # Extract card title
            card_title = node.find('h5', class_='card-title').text.strip()
            
            # Extract available space under sjc-parking-meter if available
            meter_description = node.find('div', class_='meter-description')
            if meter_description:
                available_space = meter_description.text.strip()
                
                parking_data.append({
                    "Title": card_title,
                    "Available Spots": available_space
                })
                # Check if location already exists in the database
                existing_location = Locations.objects.filter(fsLocationName=card_title,fsPartnerId=partnerid).first()
                if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots = available_space
                    existing_location.save()
                else:
                    # Create new record
                    new_parking = Locations(
                            fsPartnerId=partnerid,
                            fsLocationName=card_title,
                            fiParkingSlots=available_space,
                        )
                    new_parking.save()     

        # Close the WebDriver
        driver.quit()

        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        return json_data


