from selenium import webdriver
from bs4 import BeautifulSoup
from flask import jsonify
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():
    site_name="Aspen/Pitkin County 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.aspenairport.com/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)
    
    # Get the page source
    page_source = driver.page_source
    # Extract the HTML content
    html = page_source
    # Parse the HTML
    soup = BeautifulSoup(html, 'html.parser')
    
    # Find all parent divs containing parking information
    parent_div1 = soup.find("div",class_="chart-wrap")
    if parent_div1 is None or not parent_div1:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:
    
        parking_div = parent_div1.find_all("div",class_="lot-wrap")
        # Initialize list to store data
        parking_data = []

        # Extract data from each parent div
        for parent_div in parking_div:
            try:
                p_title = parent_div.find(class_='lot-title').text
                available_spots = parent_div.find(class_='lot-content').find(class_='percentage').text
                # Store data in dictionary
                parking_data.append({
                    'Title': p_title,
                    'Available Spots': available_spots +" Full",
                })
                # Check if location already exists in the database
                existing_location = Locations.objects.filter(fsLocationName=p_title,fsPartnerId=partnerid).first()
                if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots = available_spots +" Full"
                    existing_location.save()
                else:
                    # Create new record
                    new_parking = Locations(
                        fsPartnerId=partnerid,
                        fsLocationName=p_title,
                        fiParkingSlots=available_spots+" Full",
                    )
                    new_parking.save()
                
            except AttributeError:
                # Skip this parent div if it doesn't contain the expected elements
                continue
            # Check if parking levels exist under this parent div
            
                

        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        return json_data
