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="Baltimore/Washington International Thurgood Marshall 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://bwiairport.com/to-from-bwi/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")
    parking_data =[]
    # Find all articles containing parking lot data
    parking_items = soup.find_all(class_="parking_item")

    if parking_items is None or not parking_items:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:

        # Extract parking item  type and spaces
        for item in parking_items:
            item_type = item.find(class_="parking_item_type").text.strip()
            item_spaces = item.find(class_="parking_item_spaces").text.strip().replace('\n', ' ').replace('  ', '')
            parking_data.append({
                "Title": item_type,
                "Available Spots": item_spaces
            })
    # Check if location already exists in the database
            existing_location = Locations.objects.filter(fsLocationName=item_type,fsPartnerId=partnerid).first()
            if existing_location:
                # Update existing record
                existing_location.fiParkingSlots = item_spaces
                existing_location.save()
            else:
                # Create new record
                new_parking = Locations(
                        fsPartnerId=partnerid,
                        fsLocationName=item_type,
                        fiParkingSlots=item_spaces,
                    )
                new_parking.save()           
        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        return json_data

