from datetime import datetime

class SyncController:
    """Handles GPS to RTC synchronization operations"""
    
    def __init__(self, rtc, gps_reader, status_callback=None):
        self.rtc = rtc
        self.gps_reader = gps_reader
        self.status_callback = status_callback or (lambda msg, color=None: print(f"[SYNC] {msg}"))
        
        self.sync_in_progress = False
        self.gps_time_obj = None
        self.gps_sats = 0
        
        # Sync result callbacks
        self.sync_success_callback = None
        self.sync_error_callback = None
    
    def update_gps_data(self, gps_time, gps_sats):
        """Update GPS data from GPS reader"""
        self.gps_time_obj = gps_time
        self.gps_sats = gps_sats
    
    def sync_rtc_time(self, success_callback=None, error_callback=None):
        """
        Initiate GPS to RTC synchronization
        
        Args:
            success_callback: Function to call on successful sync (sync_time)
            error_callback: Function to call on sync error (error)
        """
        if not self.gps_time_obj:
            self.status_callback("No GPS time available.", "red")
            if error_callback:
                error_callback("No GPS time available")
            return False
            
        if self.gps_sats < 4:
            self.status_callback("Not enough satellites (need 4+)", "red")
            if error_callback:
                error_callback("Not enough satellites")
            return False
            
        if self.sync_in_progress:
            self.status_callback("Sync already in progress...", "orange")
            return False
            
        # Store callbacks
        self.sync_success_callback = success_callback
        self.sync_error_callback = error_callback
        
        # Start sync process
        self.sync_in_progress = True
        self.status_callback("Waiting for GPS second boundary...", "orange")
        
        # Request sync from GPS reader
        self.gps_reader.request_sync()
        return True
    
    def handle_sync(self, sync_time):
        """Handle the actual RTC synchronization (called by GPS reader)"""
        try:
            self.rtc.write_time(sync_time)
            print(f"[SYNC] Successfully wrote {sync_time} to RTC at second boundary")
            
            if self.sync_success_callback:
                self.sync_success_callback(sync_time)
            
            self._sync_success(sync_time)
            
        except Exception as e:
            print(f"[SYNC ERROR] {e}")
            
            if self.sync_error_callback:
                self.sync_error_callback(e)
            
            self._sync_error(e)
    
    def _sync_success(self, sync_time):
        """Handle successful sync"""
        sync_str = sync_time.strftime("%Y-%m-%d %H:%M:%S")
        self.status_callback("RTC synced successfully!", "green")
        self.sync_in_progress = False
    
    def _sync_error(self, error):
        """Handle sync error"""
        self.status_callback("RTC sync failed!", "red")
        self.sync_in_progress = False
    
    def is_sync_in_progress(self):
        """Check if sync is currently in progress"""
        return self.sync_in_progress
    
    def get_sync_status(self):
        """Get current sync status information"""
        return {
            'in_progress': self.sync_in_progress,
            'gps_time_available': self.gps_time_obj is not None,
            'sufficient_satellites': self.gps_sats >= 4,
            'satellite_count': self.gps_sats
        }