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="Sacramento 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://sacramento.aero/smf/to-and-from/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')

        parking_data =[]
        # Find all rows with parking information
        parking_rows = soup.find_all(class_='row-parking')
        if parking_rows is None or not parking_rows:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

        else:

            # Extract lot names and vacant spaces
            for row in parking_rows:
                lot_name = row.find('h2').text
                if row.find(class_='meter-vacant'):
                    vacant_space = row.find(class_='meter-vacant').text
                    parking_data.append({
                        "Title": lot_name, "Available Spots": vacant_space
                    })
                    # Check if location already exists in the database
                    if not Locations.objects(fsLocationName=lot_name).first():
                        new_parking = Locations(
                                fsPartnerId=partnerid,
                                fsLocationName=lot_name,
                                fiParkingSlots=vacant_space,
                            )
                        new_parking.save()
                    else:
                        vacant_space = row.find('p').text
                        parking_data.append({
                            "Title": lot_name, "Available Spots": vacant_space
                        })
                        # Check if location already exists in the database
                        existing_location = Locations.objects.filter(fsLocationName=lot_name,fsPartnerId=partnerid).first()
                        print(existing_location,vacant_space)
                        if existing_location:
                                # Update existing record
                                existing_location.fiParkingSlots = vacant_space
                                existing_location.save()
                        else:
                                # Create new record
                            new_parking = Locations(
                                                fsPartnerId=partnerid,
                                                fsLocationName=lot_name,
                                                fiParkingSlots=vacant_space
                                            
                                            )
                            new_parking.save()

            # Convert the list of dictionaries to JSON
            json_data = json.dumps(parking_data)

            return json_data

