import time
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():
    site_name="Louis Armstrong New Orleans 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://flymsy.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)
    time.sleep(2)  # Adjust the sleep time as needed
    
    # Get the page source
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html.parser')

    # Find all garageCard divs
    parent_div = soup.find(class_='parking-status')
    if parent_div is None or not parent_div:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:
        divs = parent_div.find_all('div',class_='sign')
        parking_data =[]
        # Extract title and available spots from each garageCard
        for div in divs:
            title = div.find('h3').find('span').text.strip()
            available_spots = div.find('progress').find_next_sibling('span').text.strip()
            parking_data.append({
                "Title": title, "Available Spots": available_spots
            })
            # 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 = available_spots
                existing_location.save()
            else:
                # Create new record
                new_parking = Locations(
                        fsPartnerId=partnerid,
                        fsLocationName=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

