import requests
from bs4 import BeautifulSoup
import json
from models.models import Partners,Locations
from notify import send_email

def get_json_data():
    site_name="Phoenix-Mesa Gateway 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.gatewayairport.com/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
            parking_lots = soup.find_all('div', class_='tile')
            if parking_lots is None or not parking_lots:
                send_email(site_name)
                json_data ={'message': 'Data not received'}
                return json_data
            else:
                parking_data=[]
                # Loop through each parking lot and extract lot name and available spaces
                for lot in parking_lots:
                   
                    lot_name = lot.find('span', class_='lotName').text.strip()
                    spaces_available = lot.find('span', class_='spacesAvailableNumber').text.strip()
                    
                    parking_data.append({
                            "Title": lot_name, "Available Spots": spaces_available +" Available"
                        })
                    
                    # Check if location already exists in the database
                    existing_location = Locations.objects.filter(fsLocationName=lot_name,fsPartnerId=partnerid).first()
                    if existing_location:
                            # Update existing record
                        existing_location.fiParkingSlots = spaces_available +" Available"
                        existing_location.save()
                    else:
                            # Create new record
                        new_parking = Locations(
                                    fsPartnerId=partnerid,
                                    fsLocationName=lot_name,
                                    fiParkingSlots=spaces_available+" Available",
                                )
                        new_parking.save() 

                    # Convert the list of dictionaries to JSON
                json_data = json.dumps(parking_data)

                return json_data

