import json
import time
from bs4 import BeautifulSoup
from selenium import webdriver
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="Minneapolis–Saint Paul 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.mspairport.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
    # Extract the HTML content
    # Parse the HTML
    # Parse the HTML
    soup = BeautifulSoup(html, 'html.parser')

    # Find all parent divs containing parking information
    parent_divs = soup.find('div',class_="parking-lot-status-block__content")
    if parent_divs is None or not parent_divs:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

    else:
        child_divs = parent_divs.find_all('div',class_="parking-ramp")
        # Initialize list to store data
        parking_data = []

        # Extract title, spaces, and type
        for row in child_divs:
            title = row.find("div",class_="parking-ramp__name").text.strip()
            space = row.find("div",class_="parking-ramp__capacity").text.strip()
            
            parking_data.append({
                'Title': title,
                'Available Spots': space,
            })
            # Check if location already exists in the database
            existing_location = Locations.objects.filter(fsLocationName=title,fsPartnerId=partnerid).first()
            if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots = space
                    existing_location.save()
            else:
                    # Create new record
                new_parking = Locations(
                                    fsPartnerId=partnerid,
                                    fsLocationName=title,
                                    fiParkingSlots=space,
                                )
                new_parking.save()

        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
