import os
import time
import requests
import xml.etree.ElementTree as ET
from datetime import datetime

# Function to parse the 'speed.xml' file and extract the speed value
def parse_speed_from_xml(xml_file):
    try:
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for elem in root.iter('Serve'):
            if 'Speed' in elem.attrib:
                speed_str = elem.attrib['Speed']
                return float(speed_str), ET.tostring(elem, encoding="unicode")
    except Exception as e:
        print(f"Error parsing XML: {e}")
    return None, None

# Function to send HTTP POST request
def send_http_post(speed_value, xml_content):
    hawkeye_time_raw = int((datetime.now() - datetime(2000, 1, 1)).total_seconds())
    
    data = {
        "Hawkeye Time (Date String)": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
        "Hawkeye Time (Raw)": hawkeye_time_raw,
        "Speed": speed_value,
        "Unit": "KPH",
        "XML_Content": xml_content  # Add XML content to the data
    }

    try:
        response = requests.post("http://10.10.1.201:40000/api/data", json=data)
        response.raise_for_status()
        print(f"HTTP POST Request Successful. Speed: {speed_value}, Raw Time: {hawkeye_time_raw}")
    except requests.exceptions.RequestException as e:
        print(f"HTTP POST Request Failed: {e}")

# Function to check for file modification
def check_file_modification(xml_file, last_modification_time):
    current_modification_time = os.path.getmtime(xml_file)
    return current_modification_time != last_modification_time, current_modification_time

if __name__ == "__main__":
    # Define the 'speed.xml' file
    xml_file = "\\\\10.10.1.51\RealTimeTennis\DataBridge1\SpeedforIDS\speed.xml"
    
    # Initialize the last modification time
    last_modification_time = os.path.getmtime(xml_file)
    
    while True:
        file_changed, last_modification_time = check_file_modification(xml_file, last_modification_time)
        if file_changed:
            speed_value, xml_content = parse_speed_from_xml(xml_file)
            if speed_value is not None:
                print("XML Content:")
                print(xml_content)
                send_http_post(speed_value, xml_content)
        
        time.sleep(0.5)  # Check for changes every 0.5 seconds
