import requests
from datetime import datetime, timedelta


def get_received_sms():
    # Diafaan server configuration
    server_url = "http://192.168.1.113:9710/http/request-received-messages"
    username = "admin"
    password = ""

    # Optional filters (adjust as needed)
    params = {
        'username': username,
        'password': password,
        'limit': 10,  # Number of messages to retrieve
        # 'startdate': (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'),  # Last 24 hours
        # 'enddate': datetime.now().strftime('%Y-%m-%d'),
        # 'unread': 'true'  # Only get unread messages (optional)
    }

    try:
        response = requests.get(server_url, params=params)

        if response.status_code == 200:
            # Parse the response (typically CSV or XML format)
            if 'text/csv' in response.headers.get('Content-Type', ''):
                messages = parse_csv_response(response.text)
            else:
                messages = parse_xml_response(response.text)

            print(f"Retrieved {len(messages)} messages:")
            for msg in messages:
                print(f"From: {msg['sender']}, Received: {msg['date']}, Message: {msg['text']}")

            return messages
        else:
            print(f"Failed to retrieve messages. Status code: {response.status_code}")
            print("Response:", response.text)
            return None

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None


def parse_csv_response(csv_data):
    """Parse CSV formatted response from Diafaan"""
    messages = []
    for line in csv_data.splitlines()[1:]:  # Skip header
        if line.strip():
            parts = line.split(',')
            if len(parts) >= 4:
                messages.append({
                    'id': parts[0],
                    'date': parts[1],
                    'sender': parts[2],
                    'text': ','.join(parts[3:])  # Handle commas in message text
                })
    return messages


def parse_xml_response(xml_data):
    """Parse XML formatted response from Diafaan"""
    try:
        from xml.etree import ElementTree
        messages = []
        root = ElementTree.fromstring(xml_data)
        for msg in root.findall('message'):
            messages.append({
                'id': msg.find('id').text if msg.find('id') is not None else '',
                'date': msg.find('date').text if msg.find('date') is not None else '',
                'sender': msg.find('sender').text if msg.find('sender') is not None else '',
                'text': msg.find('text').text if msg.find('text') is not None else ''
            })
        return messages
    except Exception as e:
        print(f"Error parsing XML: {str(e)}")
        return []


# Call the function
received_messages = get_received_sms()