import time
from selenium import webdriver
from bs4 import BeautifulSoup
import json
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
from notify import send_email

def get_json_data():
    site_name="Wilmington 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://flyilg.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
    
    # Get the page source
    page_source = driver.page_source
    # Extract the HTML content
    html = page_source
    soup = BeautifulSoup(html, 'html.parser')
    p_tag = soup.find('p', class_='parking-widget-data')
    if p_tag is None or not p_tag:
            send_email(site_name)
            json_data ={'message': 'Data not received'}
            return json_data
    else:
        data_list = []
            # Initialize an empty list to store the dictionaries

            # Get the text of the <p> tag
        p_text = p_tag.get_text(separator='|', strip=True)

            # Split the text using the pipe '|' character
        p_parts = p_text.split('|')
        
        data_list.append({'title': p_parts[0].strip().replace(':',''), 'Available Spots': p_parts[1]})
        data_list.append({'title': p_parts[3].strip().replace(':',''), 'Available Spots': p_parts[4]})
        data_list.append({'title': p_parts[-2].strip().replace(':',''), 'Available Spots': p_parts[-1]})
        for item in data_list:
                title = item['title']
                available_spots = item['Available Spots']
                # 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 = available_spots
                    existing_location.save()
                else:
                    # Create new record
                    new_parking = Locations(
                        fsPartnerId=partnerid,
                        fsLocationName=title,
                        fiParkingSlots=available_spots,
                    )
                    new_parking.save()     
               
        json_data = json.dumps(data_list)

        return json_data

