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="John Glenn Columbus 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://flycolumbus.com/passengers/parking-options/"

    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'
    elements = soup.find_all('div', class_='elementor-element')
    if elements is None or not elements:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

            
    else:

        # Initialize a list to store garage data
        garages = []

        # Loop through each element to find garage information
        for element in elements:
            # Check if the element contains garage information
            if element.find('h4', class_='elementor-heading-title'):
                garage_name = element.find('h4', class_='elementor-heading-title').text.strip().replace('\n', ' ')
                if element.find('div', class_='parkingMini'):
                    garage_status = element.find('div', class_='parkingMini').text.strip()
                garage_info = {
                    'name': garage_name,
                    'status': garage_status
                }
                exists = any(garage_info.items() <= garage.items() for garage in garages)
                if not exists:
                    garages.append(garage_info)
                    # Check if location already exists in the database
                    existing_location = Locations.objects.filter(fsLocationName=garage_name,fsPartnerId=partnerid).first()
                    if existing_location:
                        # Update existing record
                        existing_location.fiParkingSlots = garage_status
                        existing_location.save()
                    else:
                        # Create new record
                        new_parking = Locations(
                                fsPartnerId=partnerid,
                                fsLocationName=garage_name,
                                fiParkingSlots=garage_status,
                            )
                        new_parking.save()
                   
                    
            
            if element.find('h2', class_='elementor-heading-title'):
                garage_name1 = element.find('h2', class_='elementor-heading-title').text.strip().replace('\n', ' ')
                if element.find('div', class_='parkingMini'):
                    garage_status1 = element.find('div', class_='parkingMini').text.strip()
                    garage_info = {
                        'Title': garage_name1,
                        'Available Spots': garage_status1
                    }
                    
                    exists = any(garage_info.items() <= garage.items() for garage in garages)
                    if not exists:
                        garages.append(garage_info)

                        # Check if location already exists in the database
                        existing_location = Locations.objects.filter(fsLocationName=garage_name1,fsPartnerId=partnerid).first()
                        if existing_location:
                            # Update existing record
                            existing_location.fiParkingSlots = garage_status1
                            existing_location.save()
                        else:
                            # Create new record
                            new_parking = Locations(
                                fsPartnerId=partnerid,
                                fsLocationName=garage_name1,
                                fiParkingSlots=garage_status1,
                            )
                            new_parking.save()
                       
                
        # Convert the list of dictionaries to JSON
        json_data = json.dumps(garages)
        driver.quit()
        return json_data
