import pyautogui
import time
import db
import threading

# Placeholder for playback state
_playback_thread = None
_playing = False
_paused = False


def play_playlist(playlist_id, on_click_callback=None):
    """
    Play back the clicks and keyboard events for the given playlist, simulating original timing and order.
    Optionally provide on_click_callback(x, y) to be called before each click.
    """
    global _playback_thread, _playing, _paused
    if _playback_thread and _playback_thread.is_alive():
        return  # Already playing
    _playing = True
    _paused = False
    # Load clicks and keyboard events
    events = load_merged_events(playlist_id)
    if not events:
        return
    def playback():
        global _playing, _paused
        prev_time = 0
        for event in events:
            if not _playing:
                break
            while _paused:
                time.sleep(0.1)
            # Wait for the interval between events
            interval = event['timestamp'] - prev_time
            if interval > 0:
                time.sleep(interval)
            if event['type'] == 'click':
                # Mouse click event
                if on_click_callback:
                    on_click_callback(event['x'], event['y'])
                pyautogui.click(event['x'], event['y'])
            elif event['type'] == 'key':
                # Keyboard event
                # Use lazy import for pyautogui if needed
                if event['event_type'] == 'press':
                    pyautogui.keyDown(event['key'])
                elif event['event_type'] == 'release':
                    pyautogui.keyUp(event['key'])
            prev_time = event['timestamp']
        _playing = False
    _playback_thread = threading.Thread(target=playback)
    _playback_thread.start()


def pause_playback():
    """Pause the current playback session."""
    global _paused
    _paused = True


def stop_playback():
    """Stop the current playback session and reset state."""
    global _playing, _paused
    _playing = False
    _paused = False


def load_clicks(playlist_id):
    """Load clicks from the database for the given playlist."""
    conn = db.get_connection()
    cur = conn.cursor()
    cur.execute("SELECT x, y, timestamp FROM Clicks WHERE playlist_id = ? ORDER BY timestamp ASC", (playlist_id,))
    rows = cur.fetchall()
    conn.close()
    return [{'x': row[0], 'y': row[1], 'timestamp': row[2]} for row in rows]

def load_merged_events(playlist_id):
    """
    Load clicks and keyboard events from the database, merge them by timestamp, and return a sorted list.
    """
    conn = db.get_connection()
    cur = conn.cursor()
    # Load clicks
    cur.execute("SELECT x, y, timestamp FROM Clicks WHERE playlist_id = ? ORDER BY timestamp ASC", (playlist_id,))
    clicks = [{'type': 'click', 'x': row[0], 'y': row[1], 'timestamp': row[2]} for row in cur.fetchall()]
    # Load keyboard events
    cur.execute("SELECT key, event_type, timestamp FROM KeyboardEvents WHERE playlist_id = ? ORDER BY timestamp ASC", (playlist_id,))
    keys = [{'type': 'key', 'key': row[0], 'event_type': row[1], 'timestamp': row[2]} for row in cur.fetchall()]
    conn.close()
    # Merge and sort by timestamp
    events = clicks + keys
    events.sort(key=lambda e: e['timestamp'])
    return events

# Lazy loading example: only import heavy modules when needed
def lazy_import_pynput():
    global mouse
    import pynput.mouse as mouse
    return mouse 