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="Orlando International Airport"

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://orlandoairports.net/parking-transportation/parking/")

        time.sleep(2)  # Adjust the sleep time as needed
        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', class_='cascading-grid--item-wrapper', recursive=False):
                heading_tag = li.find('h3', class_='item--heading')
                status_open = li.find('span', class_='status-open')
                status_full = li.find('span', class_='status-full')
                if heading_tag and (status_open or status_full):
                    item = {
                        'Title': heading_tag.get_text(strip=True),
                        'Available Spots': status_open.get_text(strip=True) if status_open else status_full.get_text(strip=True),
                    }
                    items.append(item)
            return items
        list_items = extract_list_items(soup.find('ul', class_='cascading-grid--container'))
        
        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'],fsPartnerId=partnerid).first()
                if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots = item['Available Spots']
                    existing_location.save()
                else:
                    # Create new record
                    new_parking = Locations(
                        fsPartnerId=partnerid,
                        fsLocationName=item['Title'],
                        fiParkingSlots= item['Available Spots'],
                    )
                    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)
        pass