import requests
from bs4 import BeautifulSoup
import json
from models.models import Locations,Partners
from notify import send_email

def get_json_data():
    
    site_name="San Francisco 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.flysfo.com/passengers/parking"

    # Send a GET request to the URL
    response = requests.get(url)

    if response.status_code == 200:
        # Extract the HTML content
        html = response.text
        soup = BeautifulSoup(html, 'html.parser')

        # Find all garageCard divs
        garage_cards = soup.find_all(class_='garageCard')
        if garage_cards is None or not garage_cards:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

            
        else:
            parking_data =[]
            # Extract title and available spots from each garageCard
            for garage_card in garage_cards:
                title = garage_card.find(class_='garageCard__title').text.strip()
                available_spots = garage_card.find(class_='garageCard__infos__spots').text.strip()
                parking_data.append({
                    "Title": title, "Available Spots": available_spots
                })
                
                # Check if location already exists in the database
                existing_location = Locations.objects.filter(fsLocationName=title,fsPartnerId=partnerid).first()
                if existing_location:
                    # Update existing record
                    existing_location.fiParkingSlots = available_spots
                    existing_location.save()
                else:
                    # Create new record
                    new_parking = Locations(
                            fsPartnerId=partnerid,
                            fsLocationName=title,
                            fiParkingSlots=available_spots,
                        )
                    new_parking.save() 

            # Convert the list of dictionaries to JSON
            json_data = json.dumps(parking_data)

            return json_data

