import requests
from bs4 import BeautifulSoup
import json
from models.models import Locations,Partners,Level
from notify import send_email

def get_json_data():
    site_name = "Eppley Airfield"
    partners = Partners.objects(fsBusinessName=site_name)

    if not partners:
        return {'message': 'No partners found'}

    for partner in partners:
        locations = Locations.objects(fsPartnerId=partner.id)
        partnerid = str(partner.id)

        # URL of the webpage to scrape
        url = "https://www.flyoma.com/parking/#1562776791850-cb56232b-3903"

        # Send a GET request to the URL
        response = requests.get(url)

        if response.status_code == 200:
            # Extract the HTML content
            html = response.text
            # Parse the HTML
            soup = BeautifulSoup(html, 'html.parser')

            # Find all parent divs containing parking information
            parent_divs = soup.find_all(lambda tag: tag.name == 'div' and 
                                            tag.has_attr('class') and 
                                            'vc_col-sm-12' in tag['class'] and 
                                            'wpb_column' in tag['class'] and 
                                            'jupiter-donut-' in tag['class'])
            if not parent_divs:
                send_email(site_name)
                return {'message': 'Data not received'}

            # Initialize list to store data
            parking_data = []

            # Extract data from each parent div
            for parent_div in parent_divs:
                try:
                    p_title = parent_div.find(class_='parking-bar-block_title').text
                    p_title = p_title.split(":")[0]
                    available_spots = parent_div.find(class_='parking-bar-block_info_available').find(class_='parking-bar-block_info_data').text
                    occupied_spots = parent_div.find(class_='parking-bar-block_info_occupied').find(class_='parking-bar-block_info_data').text

                    # Check if there are nested levels
                    is_vc_tta = parent_div.find(class_='vc_tta-panels')
                    levels = []

                    if is_vc_tta:
                        # Extract data from parking levels
                        parking_levels = is_vc_tta.find_all(class_='parking-bar-block')
                        for level in parking_levels:
                            try:
                                level_title = level.find(class_='parking-bar-block_title').text
                                level_available_spots = level.find(class_='parking-bar-block_info_available').find(class_='parking-bar-block_info_data').text
                                level_occupied_spots = level.find(class_='parking-bar-block_info_occupied').find(class_='parking-bar-block_info_data').text
                                levels.append({
                                    'Title': level_title,
                                    'Available Spots': level_available_spots +" Available",
                                    'Occupied Spots': level_occupied_spots+" Occupied"
                                })
                            except AttributeError:
                                continue

                    # Append parent parking data
                    parking_data.append({
                        'Title': p_title,
                        'Available Spots': available_spots+" Available",
                        'Occupied Spots': occupied_spots+" Occupied",
                        'Levels': levels
                    })

                    # Check if location already exists in the database
                    existing_location = Locations.objects.filter(fsLocationName=p_title,fsPartnerId=partnerid).first()
                    if existing_location:
                        # Update existing record
                        existing_location.fiParkingSlots = available_spots +" Available"
                        existing_location.fsoccupied_spots = occupied_spots +" Occupied"

                        # Existing levels by title for quick lookup
                        existing_levels = {level.title: level for level in existing_location.fllevels}

                        for level_data in levels:
                            level_title = level_data['Title']
                            if level_title in existing_levels:
                                # Update existing level
                                level = existing_levels[level_title]
                                level.available_spots = level_data['Available Spots']+" Available"
                                level.occupied_spots = level_data['Occupied Spots']+" Occupied"
                            else:
                                # Create new level
                                new_level = Level(
                                    title=level_title,
                                    available_spots=level_data['Available Spots']+" Available",
                                    occupied_spots=level_data['Occupied Spots']+" Occupied",
                                    parking_id=str(existing_location.id)
                                )
                                existing_location.fllevels.append(new_level)

                        existing_location.save()
                    else:
                        # Create new location
                        new_parking = Locations(
                            fsPartnerId=partnerid,
                            fsLocationName=p_title,
                            fiParkingSlots=available_spots+" Available",
                            fsoccupied_spots=occupied_spots+" Occupied"
                        )
                        for level_data in levels:
                            new_level = Level(
                                title=level_data['Title'],
                                available_spots=level_data['Available Spots']+" Available",
                                occupied_spots=level_data['Occupied Spots']+" Occupied",
                                parking_id=new_parking.id
                            )
                            new_parking.fllevels.append(new_level)
                        new_parking.save()

                except AttributeError:
                    continue

            # Convert the list of dictionaries to JSON
            json_data = json.dumps(parking_data)
            return json_data
        else:
            return {'message': 'Failed to retrieve data from the website'}