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,Level
from notify import send_email

def get_json_data():
    site_name = "Indianapolis International Airport"
    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.ind.com/parking"

        options = Options()
        options.add_argument('--headless')
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
        
        # Load the webpage
        driver.get(url)
        time.sleep(2)  # Adjust the sleep time as needed
        expand_button = driver.find_element(By.XPATH, "//button[@class='parking__subtitle pricing-expand']")
        expand_button.click()

        # Wait for the page to load after clicking the button
        time.sleep(2)  # Adjust the sleep time as needed
        # Get the page source
        page_source = driver.page_source
        # Parse the HTML
        soup = BeautifulSoup(page_source, 'html.parser')

        # Find all parent divs containing parking information
        parent_divs = soup.find_all('div', class_="parking__row")
        if not parent_divs:
            send_email(site_name)
            driver.quit()
            return {'message': 'Data not received'}

        # Initialize list to store data
        parking_data = []

        # Extract title, spaces, and type
        for row in parent_divs[1:]:
            columns = row.find_all('div', class_="parking__column")
            title = columns[0].find("button").text.strip()
            percentage = columns[1].find("b").text.strip()
            if percentage.upper() not in ["OPEN", "FULL", "CLOSED"]:
                space = int(percentage.replace("%", ""))
                space = str(space) + '% Full'
            else:
                space = percentage

            # Extract sub-level information
            sub_levels = []
            sub_level_rows = row.find_all('tr')
            for sub_row in sub_level_rows:
                sub_columns = sub_row.find_all('td')
                sub_level_title = sub_columns[0].text.strip()
                sub_level_percentage = sub_columns[1].find("b").text.strip()
                sub_levels.append({
                    'Title': sub_level_title,
                    'Available Spots': sub_level_percentage+ " Full" if sub_level_percentage != "FULL" else sub_level_percentage
                })

            # Append parking data
            parking_data.append({
                'Title': title,
                'Available Spots': space,
                'Levels': sub_levels
            })

            # 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 = space
                existing_levels = {level.title: level for level in existing_location.fllevels}

                for level_data in sub_levels:
                    available_spots = level_data['Available Spots']
                    level_title = level_data['Title']

                    if level_title in existing_levels:
                        # Update existing level
                        level = existing_levels[level_title]
                        level.available_spots = available_spots
                    else:
                        # Create new level
                        parking_level = Level(
                            title=level_title,
                            available_spots=available_spots,
                            parking_id=str(existing_location.id)
                        )
                        existing_location.fllevels.append(parking_level)

                existing_location.save()
            else:
                # Create new location
                new_parking = Locations(
                    fsPartnerId=partnerid,
                    fsLocationName=title,
                    fiParkingSlots=space,
                )
                for level_data in sub_levels:
                    available_spots = level_data['Available Spots']
                    level_title = level_data['Title']
                    parking_level = Level(
                        title=level_title,
                        available_spots=available_spots,
                        parking_id=new_parking.id
                    )
                    new_parking.fllevels.append(parking_level)
                new_parking.save()

        # Convert the list of dictionaries to JSON
        json_data = json.dumps(parking_data)
        driver.quit()
        return json_data
