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="Portland 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://www.flypdx.com/Parking"
    options = Options()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36')
    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('div', class_='accordion')

    if elements is None or not elements:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

            
    else:
        card = elements.find_all('div', class_='card')
    

        # Initialize a list to store garage data
        parking_data = []

        # Loop through each element to find garage information
        for element in card:
            # Check if the element contains garage informations
            if element.find('button', class_='collapsed'):
                p_element = element.find('div', class_='card-header')
                p_classs= p_element.get('id')
                driver.find_element(By.XPATH,f'//div[@id="{p_classs}"]//button').click()
                time.sleep(2) 
            name = element.find('span', class_='lot-title').text.strip()
            if element.find('div', class_='parking'):
                perc_full = element.find('div', class_='parking').text.strip().replace('\n',' ').replace("  ", "").replace('Open ',"")
                
            parking_info = {
                'Title': name,
                'Available Spots': perc_full
            }
            parking_data.append(parking_info)
            # Check if location already exists in the database
            existing_location = Locations.objects.filter(fsLocationName=name,fsPartnerId=partnerid).first()
            print(existing_location)
            if existing_location:
                    # Update existing record
                existing_location.fiParkingSlots = perc_full
                existing_location.save()
            else:
                # Create new record
                new_parking = Locations(
                            fsPartnerId=partnerid,
                            fsLocationName=name,
                            fiParkingSlots=perc_full,
                        )
                new_parking.save()     
            
        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
    
