import os
import threading
from datetime import datetime

class DataLogger:
    """Handles logging of CSEM Triggerbox operations"""
    
    def __init__(self, log_directory="/home/morepork/Documents/CSEM/logs"):
        self.log_directory = log_directory
        self.log_file = None
        self.gps_log_file = None  # New GPS log file
        self.is_logging = False
        self.log_lock = threading.Lock()
        
        # Create log directory if it doesn't exist
        os.makedirs(self.log_directory, exist_ok=True)
    
    def set_gps_log_path(self, path):
        """Set the GPS log file path (from GPSReader)"""
        self.gps_log_path = path

    def get_current_gps_log_file(self):
        """Return the current GPS log file path"""
        return self.gps_log_path
        
    
    
    def start_logging(self, frequency, transmit_time, pause_time, rpi_time=None, gps_time=None, rtc_time=None, lat=None, lon=None, sats=None):
        """
        Start a new log file with header information
        
        Args:
            frequency: Transmission frequency in Hz
            transmit_time: Transmit duration in seconds
            pause_time: Pause duration in seconds
            rpi_time: Current RPI time
            gps_time: Current GPS time
            rtc_time: Current RTC time
            lat: GPS latitude
            lon: GPS longitude
            sats: Number of GPS satellites
        """
        with self.log_lock:
            if self.is_logging:
                self.stop_logging()  # Close any existing log
            
            # Create timestamped filename
            now = datetime.utcnow() if rpi_time is None else rpi_time
            filename = now.strftime("%m%d%y_%H%M.txt")
            gps_filename = now.strftime("%m%d%y_%H%M_GPS.txt")
            filepath = os.path.join(self.log_directory, filename)
            gps_filepath = os.path.join(self.log_directory, gps_filename)
            
            try:
                # Open main log file
                self.log_file = open(filepath, 'w')
                
                # Open GPS log file
                self.gps_log_file = open(gps_filepath, 'w')
                
                self.is_logging = True
                
                # Write headers
                self._write_header(frequency, transmit_time, pause_time, rpi_time, gps_time, rtc_time, lat, lon, sats)
                self._write_gps_header()
                
                print(f"[LOG] Started logging to: {filepath}")
                print(f"[LOG] Started GPS logging to: {gps_filepath}")
                return True
                
            except Exception as e:
                print(f"[LOG ERROR] Failed to create log files: {e}")
                self.is_logging = False
                # Clean up any partially opened files
                if self.log_file:
                    try:
                        self.log_file.close()
                    except:
                        pass
                    self.log_file = None
                if self.gps_log_file:
                    try:
                        self.gps_log_file.close()
                    except:
                        pass
                    self.gps_log_file = None
                return False
    
    def stop_logging(self):
        """Stop logging and close the current log files"""
        with self.log_lock:
            if self.is_logging:
                # Close main log file
                if self.log_file:
                    try:
                        self.log_file.write(f"\n{datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC - Logging stopped\n")
                        self.log_file.close()
                        print(f"[LOG] Stopped main logging")
                    except Exception as e:
                        print(f"[LOG ERROR] Error closing main log file: {e}")
                    finally:
                        self.log_file = None
                
                # Close GPS log file
                if self.gps_log_file:
                    try:
                        self.gps_log_file.write(f"{datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')},LOGGING_STOPPED\n")
                        self.gps_log_file.close()
                        print(f"[LOG] Stopped GPS logging")
                    except Exception as e:
                        print(f"[LOG ERROR] Error closing GPS log file: {e}")
                    finally:
                        self.gps_log_file = None
                        
                self.is_logging = False
    
    def log_event(self, event_type, message=""):
        """
        Log an event with timestamp
        
        Args:
            event_type: Type of event ('COUNTDOWN', 'TRANSMIT_START', 'TRANSMIT_STOP', 'PAUSE_START', 'PAUSE_STOP', etc.)
            message: Additional message or data
        """
        if not self.is_logging or not self.log_file:
            return
        
        with self.log_lock:
            try:
                timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
                log_line = f"{timestamp} UTC - {event_type}"
                if message:
                    log_line += f": {message}"
                log_line += "\n"
                
                self.log_file.write(log_line)
                self.log_file.flush()  # Ensure data is written immediately
                
            except Exception as e:
                print(f"[LOG ERROR] Failed to write log entry: {e}")
    
    def log_gps_position(self, lat, lon):
        """
        Log GPS position data to GPS log file
        
        Args:
            lat: Latitude string (e.g., "36.12345 N")
            lon: Longitude string (e.g., "121.67890 W")
        """
        if not self.is_logging or not self.gps_log_file:
            return
        
        # Only log if we have valid GPS data
        if lat == 'N/A' or lon == 'N/A':
            return
            
        with self.log_lock:
            try:
                timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
                gps_line = f"{timestamp},{lat},{lon}\n"
                
                self.gps_log_file.write(gps_line)
                self.gps_log_file.flush()  # Ensure data is written immediately
                
            except Exception as e:
                print(f"[GPS LOG ERROR] Failed to write GPS entry: {e}")
    
    def log_countdown(self, countdown_text):
        """Log countdown events"""
        if "00:00" in countdown_text:
            self.log_event("COUNTDOWN_COMPLETE", "Countdown reached zero")
        else:
            # Extract just the time part for cleaner logs
            time_part = countdown_text.replace("Countdown: ", "")
            self.log_event("COUNTDOWN", time_part)
    
    def log_transmission_start(self, frequency):
        """Log transmission start"""
        self.log_event("TRANSMIT_START", f"Started transmission at {frequency} Hz")
    
    def log_transmission_stop(self):
        """Log transmission stop"""
        self.log_event("TRANSMIT_STOP", "Stopped transmission")
    
    def log_pause_start(self, duration):
        """Log pause start"""
        self.log_event("PAUSE_START", f"Started {duration}s pause")
    
    def log_pause_complete(self):
        """Log pause completion"""
        self.log_event("PAUSE_COMPLETE", "Pause period ended")
    
    def log_cycle_complete(self):
        """Log complete cycle"""
        self.log_event("CYCLE_COMPLETE", "Transmission cycle completed")
    
    def log_manual_stop(self):
        """Log manual stop"""
        self.log_event("MANUAL_STOP", "Transmission manually stopped")
    
    def is_logging_active(self):
        """Check if logging is currently active"""
        return self.is_logging
    
    def get_current_log_file(self):
        """Get the current log file path"""
        if self.log_file:
            return self.log_file.name
        return None
    
    def get_current_gps_log_file(self):
        """Get the current GPS log file path"""
        if self.gps_log_file:
            return self.gps_log_file.name
        return None
    
    def _write_header(self, frequency, transmit_time, pause_time, rpi_time, gps_time, rtc_time, lat, lon, sats):
        """Write log file header with session information"""
        header = []
        header.append("=" * 60)
        header.append("MBARI CSEM TRIGGERBOX LOG FILE")
        header.append("=" * 60)
        header.append(f"Log created: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC")
        header.append("")
        
        # Time information
        header.append("TIME SYNCHRONIZATION:")
        if rpi_time:
            header.append(f"  RPI Time (UTC): {rpi_time.strftime('%Y-%m-%d %H:%M:%S')}")
        else:
            header.append("  RPI Time (UTC): Not available")
        
        if gps_time:
            header.append(f"  GPS Time (UTC): {gps_time.strftime('%Y-%m-%d %H:%M:%S')}")
        else:
            header.append("  GPS Time (UTC): Not available")
        
        if rtc_time:
            header.append(f"  RTC Time (UTC): {rtc_time.strftime('%Y-%m-%d %H:%M:%S')}")
        else:
            header.append("  RTC Time (UTC): Not available")
        
        header.append("")
        
        # GPS Position
        header.append("GPS POSITION:")
        header.append(f"  Latitude: {lat if lat and lat != 'N/A' else 'Not available'}")
        header.append(f"  Longitude: {lon if lon and lon != 'N/A' else 'Not available'}")
        header.append(f"  Satellites: {sats if sats and sats != 'N/A' else 'Not available'}")
        header.append("")
        
        # Transmission Settings
        header.append("TRANSMISSION SETTINGS:")
        header.append(f"  Frequency: {frequency:.3f} Hz")
        header.append(f"  Period: {1.0/frequency:.3f} seconds")
        header.append(f"  Transmit Time: {transmit_time} seconds")
        header.append(f"  Pause Time: {pause_time} seconds")
        header.append("")
        
        # GPIO Configuration
        header.append("GPIO CONFIGURATION:")
        header.append("  TX Status: GPIO 13 (Pin 33)")
        header.append("  Duty Signal: GPIO 6 (Pin 31)")
        header.append("  Polarity Signal: GPIO 26 (Pin 37)")
        header.append("  PPS Input: GPIO 17 (Pin 11)")
        header.append("")
        
        header.append("=" * 60)
        header.append("EVENT LOG:")
        header.append("=" * 60)
        header.append("")
        
        # Write header to file
        for line in header:
            self.log_file.write(line + "\n")
        
        self.log_file.flush()
    
    def _write_gps_header(self):
        """Write GPS log file header"""
        header = []
        header.append("# MBARI CSEM TRIGGERBOX GPS POSITION LOG")
        header.append(f"# Log created: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC")
        header.append("# Format: Timestamp,Latitude,Longitude")
        header.append("# Example: 2024-01-01 12:00:00,36.12345 N,121.67890 W")
        header.append("#")
        
        # Write header to GPS file
        for line in header:
            self.gps_log_file.write(line + "\n")
        
        self.gps_log_file.flush()


# Utility functions for easy integration
def create_logger(log_directory="/home/morepork/Documents/CSEM/logs"):
    """Create a new DataLogger instance"""
    return DataLogger(log_directory)


# Test the logger
if __name__ == "__main__":
    # Test logging functionality
    logger = DataLogger()
    
    # Test start logging
    success = logger.start_logging(
        frequency=1.5,
        transmit_time=60,
        pause_time=30,
        rpi_time=datetime.utcnow(),
        gps_time=datetime.utcnow(),
        rtc_time=datetime.utcnow(),
        lat="36.12345 N",
        lon="121.67890 W",
        sats="8"
    )
    
    if success:
        # Test logging events
        logger.log_countdown("Countdown: 01:30")
        logger.log_countdown("Countdown: 01:00")
        logger.log_countdown("Countdown: 00:30")
        logger.log_countdown("Countdown: 00:00")
        logger.log_transmission_start(1.5)
        
        # Test GPS position logging
        logger.log_gps_position("36.12345 N", "121.67890 W")
        logger.log_gps_position("36.12346 N", "121.67891 W")
        logger.log_gps_position("36.12347 N", "121.67892 W")
        
        logger.log_pause_start(30)
        logger.log_pause_complete()
        logger.log_transmission_stop()
        
        # Stop logging
        logger.stop_logging()
        
        print("Test completed successfully!")
        print(f"Main log: {logger.get_current_log_file()}")
        print(f"GPS log: {logger.get_current_gps_log_file()}")
    else:
        print("Failed to start logging!")