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,Level
from notify import send_email
site_name="John Wayne Airport"
import re

def get_json_data():
    try:
        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)
            
            
        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("https://www.ocair.com/travelers/parking-transport/parking/availability/")

        time.sleep(2)  # Adjust the sleep time as needed
        # Find and click the "Expand All" button
        expand_button = driver.find_element(By.XPATH, "//a[@id='pa-btn-expand']")
        expand_button.click()

        # Wait for the page to load after clicking the button
        time.sleep(2)  # Adjust the sleep time as needed

        # Extract the HTML content after the page has been updated
        html_code = driver.page_source

        # Close the WebDriver session
        driver.quit()

        # Parse the HTML
        soup = BeautifulSoup(html_code, 'html.parser')
        
        def extract_list_items(ul_tag):
            items = []
            for li in ul_tag.find_all('li', recursive=False):
                
                item = {
                    'Title': ''.join(li.find_all(text=True, recursive=False)).strip() ,
                    'Available Spots': li.find('div', class_='parking-stats').get_text(strip=True) if li.find('div', class_='parking-stats') else None,
                    'Levels': extract_list_items(li.find('ul', class_='expanded')) if li.find('ul') else []
                }
                items.append(item)
            return items
        list_items = extract_list_items(soup.find('ul', class_='pa-list'))
        if list_items is None or not list_items:
            send_email(site_name)
            json_data = {'message': 'Data not received'}
            return json.dumps(json_data)
        else:
            for item in list_items:
                
                # Check if location already exists in the database
                existing_location = Locations.objects(fsLocationName=item['Title']).first()
                if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots = re.sub(r'[\(\)]|\s*avail\.', '', item['Available Spots'].split()[0]) +" Available"
                    # Update existing levels
                    existing_levels = {level.title: level for level in existing_location.fllevels}
                    for level_data in item['Levels']:
                        available_spots = re.sub(r'[\(\)]|\s*avail\.', '', level_data['Available Spots'].split()[0]) +" Available"
                        title = level_data['Title']
                        if title in existing_levels:
                            # Update existing level
                            existing_level = existing_levels[title]
                            existing_level.available_spots = available_spots
                        else:
                            # Create new level
                            new_level = Level(
                                title=title,
                                available_spots=available_spots
                            )
                            existing_location.fllevels.append(new_level)
                    
                    existing_location.save()
                else:
                    # Create new record
                    new_parking = Locations(
                                    fsPartnerId=partnerid,
                                    fsLocationName=item['Title'],
                                    fiParkingSlots= re.sub(r'[\(\)]|\s*avail\.', '', item['Available Spots'].split()[0]) +" Available",
                                )
                    for level_data in item['Levels']:
                        available_spots = re.sub(r'[\(\)]|\s*avail\.', '', level_data['Available Spots'].split()[0]) +" Available"
                        title = level_data['Title']
                        parking_level = Level(
                            title=title,
                            available_spots=available_spots,
                        
                            )
                        new_parking.fllevels.append(parking_level)
                    # Save the new_parking object
                    new_parking.save()

        # Convert list_items to JSON and return if needed
        json_data = json.dumps(list_items)
        return json_data
    except:
        send_email(site_name)