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="Asheville 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://flyavl.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
    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 parent divs containing parking information
    child_divs = soup.find_all('div',class_="status")
    if child_divs is None or not child_divs:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:
        # Initialize list to store data
        parking_data = []
        # Extract title, spaces, and type
        for row in child_divs:
            data1 = row.text.strip()
            data=data1.split('–')[1].strip() 
            data2=data1.split('–')[0].strip()
            p_title=data2
            available_spots=data
            
            parking_data.append({
                'Title': p_title,
                'Available Spots': available_spots,
            })
            # 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
                existing_location.save()
            else:
                # Create new record
                new_parking = Locations(
                            fsPartnerId=partnerid,
                            fsLocationName=p_title,
                            fiParkingSlots=available_spots,
                        )
                new_parking.save()
                

    # Convert the list of dictionaries to JSON
    json_data = json.dumps(parking_data)
    driver.quit()
    return json_data
