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="Portland International Jetport"
    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://portlandjetport.org/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
    articles = soup.find_all("article", class_="node--type-parking-lot")
    if articles is None or not articles:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

    else:
        # Iterate over each article to extract facility name and status
        for article in articles:
            facility_name = article.find("span", class_="field--name-title").text.strip()
            status = article.find("div", class_="parking-status-area").find("div", class_="field__item").text.strip()
            parking_data.append({
                "Title": facility_name, "Available Spots": status
            })
            # Check if location already exists in the database
            existing_location = Locations.objects(fsLocationName=facility_name).first()
            if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots =  status
                    existing_location.save()
            else:
                    # Create new record
                new_parking = Locations(
                                    fsPartnerId=partnerid,
                                    fsLocationName=facility_name,
                                    fiParkingSlots=status,
                                )
                new_parking.save()
        json_data = json.dumps(parking_data)

        return json_data

