"""
Auto-extractor functionality for the auto clicker application.
"""

import threading
import time
import logging
from .constants import AUTO_EXTRACTOR_CHECK_INTERVAL, UI_UPDATE_DELAY, PLAYBACK_STATUS_CHECK_INTERVAL


class AutoExtractorManager:
    """Manages auto-extractor functionality."""
    
    def __init__(self, app):
        self.app = app
        
    def start_watcher(self):
        """Start the auto-extractor watcher in a background thread."""
        threading.Thread(target=self._watcher_thread, daemon=True).start()

    def _watcher_thread(self):
        """Background thread that watches for auto-extractor jobs."""
        while True:
            time.sleep(AUTO_EXTRACTOR_CHECK_INTERVAL)
            
            # Only run if app is idle (not recording or playing)
            if self.app.status_var.get() == 'Idle' and not self.app.recording:
                try:
                    self.app.status_var.set('Checking queue...')
                    job = self._get_next_job()
                    
                    if job:
                        # Just show that a job is available, don't auto-process
                        self.app.status_var.set(f'Job ready: {job.get("playlist_name", "Unknown")}')
                        logging.info(f'Auto-extractor job available: {job.get("playlist_name")} (ID: {job.get("id")})')
                        # Don't auto-process: self._process_job(job)
                        
                    # Set status back to Idle if not playing or recording and no job waiting
                    elif self.app.status_var.get() != 'Playing' and not self.app.recording:
                        self.app.status_var.set('Idle')
                        
                except Exception as e:
                    logging.error(f'Auto extractor watcher error: {e}')
                    if self.app.status_var.get() != 'Playing' and not self.app.recording:
                        self.app.status_var.set('Idle')

    def _get_next_job(self):
        """Get the next auto-extractor job from MySQL."""
        try:
            from mysql.mysql_client import get_next_auto_extractor_job
            return get_next_auto_extractor_job()
        except Exception as e:
            logging.error(f"Error getting next auto-extractor job: {e}")
            return None

    def _process_job(self, job):
        """Process an auto-extractor job."""
        playlist_name = job.get('playlist_name')
        job_id = job.get('id')
        
        if not playlist_name:
            return
            
        try:
            # Update UI and selection
            self.app.create_widgets()  # Ensure widgets are up to date
            self.app.playlist_manager.update_playlist_dropdown_selection(playlist_name)
            
            # Wait for UI update
            time.sleep(UI_UPDATE_DELAY)
            
            # Trigger playback
            self.app.after(100, self.app.playback_manager.play_playlist)
            
            # Wait for playback to finish
            while self.app.status_var.get() == 'Playing':
                time.sleep(PLAYBACK_STATUS_CHECK_INTERVAL)
                
            # Mark job as processed
            self._mark_job_processed(job_id)
            
        except Exception as e:
            logging.error(f"Error processing auto-extractor job: {e}")

    def _mark_job_processed(self, job_id):
        """Mark an auto-extractor job as processed."""
        try:
            from mysql.mysql_client import mark_auto_extractor_job_processed
            mark_auto_extractor_job_processed(job_id)
        except Exception as e:
            logging.error(f"Error marking job as processed: {e}")

    def check_queue_once(self):
        """Manually check the auto-extractor queue once."""
        self.app.show_loader('Checking queue...')
        
        try:
            job = self._get_next_job()
            
            if job:
                playlist_name = job.get('playlist_name')
                job_id = job.get('id')
                
                # Set playlist selection
                self.app.selected_playlist.set(playlist_name)
                self.app.create_widgets()  # Refresh UI to update dropdown
                
                # Wait for UI update
                time.sleep(UI_UPDATE_DELAY)
                
                # Trigger playback
                self.app.after(100, self.app.playback_manager.play_playlist)
                
                # Wait for playback to finish
                while self.app.status_var.get() == 'Playing':
                    time.sleep(PLAYBACK_STATUS_CHECK_INTERVAL)
                    
                self._mark_job_processed(job_id)
                
        except Exception as e:
            logging.error(f"Error in manual queue check: {e}")
            
        finally:
            self.app.hide_loader()