import json
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
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="Nashville 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://flynashville.com/park-at-bna"

    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 

    lot_divs = soup.find_all('div', class_='op-row')
    if lot_divs is None or not lot_divs:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:

        # 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
            lot_name = div.find('h4', class_='col-header').text.strip()
            # Find the available spots
            status = div.find('h3', class_='col-inner-header').text.strip()
            
            # Store the lot name and status spots in the dictionary
            parking_data.append({
                'Title':lot_name,
                'Available Spots':  status,
            })
            
            existing_location = Locations.objects.filter(fsLocationName=lot_name,fsPartnerId=partnerid).first()
            if existing_location:
            # Update existing record
                try:
                    existing_location.fiParkingSlots = status.strip()
                    existing_location.save()
                except Exception as e:
                    print(e.message)
            else:
            # Create new record
                new_parking = Locations(
                                    fsPartnerId=partnerid,
                                    fsLocationName=lot_name,
                                    fiParkingSlots=status.strip()
                                )
                new_parking.save()


        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
