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="Greenville-Spartanburg 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://gspairport.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 elements with class 'elementor-element'
    element = soup.find('tbody')
    if element is None or not element:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

    else:
        table_row = element.find_all('tr')

        # Initialize a list to store garage data
        parking_data = []

        # Loop through each element to find garage information
        for element in table_row:
            columns = element.find_all('td')
            
            title=columns[0].text.strip()
            available_spots= columns[-2].text.strip()
            status=columns[-1].text.strip()
            parking_data.append({
                'Title':title,
                'Available Spots':available_spots.replace(" ","")+ " Full" if available_spots != '-' else available_spots,
                'Status': status ,
            })
            existing_location = Locations.objects.filter(fsLocationName=title,fsPartnerId=partnerid).first()
            if existing_location:
            # Update existing record
                existing_location.fiParkingSlots = available_spots.replace(" ","")+ " Full"  if available_spots != '-' else available_spots
                existing_location.fsstatus=status
                existing_location.save()
            else:
            # Create new record
                new_parking = Locations(
                                fsPartnerId=partnerid,
                                fsLocationName=title,
                                fiParkingSlots=available_spots.replace(" ","")+ " Full"  if available_spots != '-' else available_spots,
                                fsstatus=status
                            )
                new_parking.save()
                

        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
