import requests
from bs4 import BeautifulSoup
import json
from models.models import Partners,Locations
from notify import send_email
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
def get_json_data():
    site_name="Phoenix Sky Harbor 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.skyharbor.com/parking/"

    # Send a GET request to the URL
    response = requests.get(url)

    if response.status_code == 200:
        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)
        driver.get(url)
        time.sleep(2)
        page_source = driver.page_source
        # Extract the HTML content
        html = page_source
        soup = BeautifulSoup(html, 'html.parser')
       
        # Find all sections with class="scroll-item"
        sections = soup.find_all('div', class_='section')
        if sections is None or not sections:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data

        else:
            parking_data=[]
            # Loop through each section
            for section in sections:
                # Extract section title
                section_title = section.find('h3').text.strip()
                # Find all indicator rows
                indicator_rows = section.find_all('div', class_='indicator-name')
                
                # Loop through each indicator row
                for indicator_row in indicator_rows:
                    # Extract lot title and capacity open
                    # lot_title = indicator_row.find('strong').text.strip()
                    strong_tag = indicator_row.find('strong')
                    
                    # Initialize an empty string to hold the final text
                    lot_title = ''
                    
                    # Iterate over children of <strong> tag
                    for child in strong_tag.children:
                        if child.name is None:  # Text nodes
                            lot_title += child.strip()
                        # Ignore other tags like <span>
                    
                    if indicator_row.find('span', class_='capacity-open'):
                        capacity_open = indicator_row.find('span', class_='capacity-open').text.strip()
                        parking_data.append({
                            "Title": lot_title, "Available Spots": capacity_open
                        })
                        # Check if location already exists in the database
                        existing_location = Locations.objects.filter(fsLocationName=lot_title,fsPartnerId=partnerid).first()
                        if existing_location:
                                # Update existing record
                                existing_location.fiParkingSlots = capacity_open

                                existing_location.save()
                        else:
                                # Create new record
                            new_parking = Locations(
                                                fsPartnerId=partnerid,
                                                fsLocationName=lot_title,
                                                fiParkingSlots=capacity_open
                                            
                                            )
                            new_parking.save()

            # Convert the list of dictionaries to JSON
            json_data = json.dumps(parking_data)

            return json_data

