import rumps
import sys
import os
from datetime import datetime
from . import keka

class KekaStatusBarApp(rumps.App):
    def __init__(self):
        super(KekaStatusBarApp, self).__init__("Keka: Loading...")
        self.has_notified = False
        
        # We fetch the initial data once during startup
        try:
            self.payload = keka.load_cached_or_fetch(None)
        except Exception as e:
            self.title = "Keka: Error"
            self.payload = None

    @rumps.timer(1)
    def update_clock(self, _):
        if not self.payload:
            return
            
        try:
            cached_effective_hours = self.payload["effective_hours"]
            last_login = self.payload.get("last_login")
            
            if not last_login:
                self.title = "Keka: No logs today"
                self.menu.clear()
                refresh_btn = rumps.MenuItem("Refresh from Server")
                refresh_btn.set_callback(self.manual_refresh)
                self.menu.add(refresh_btn)
                self.menu.add(rumps.MenuItem("Quit", callback=rumps.quit_application))
                return
                
            cached_effective_seconds = keka.to_seconds(cached_effective_hours)
            last_login_seconds = keka.to_seconds(last_login)
            
            now = datetime.now()
            now_seconds = now.hour * 3600 + now.minute * 60 + now.second
            
            elapsed_seconds = now_seconds - last_login_seconds
            if elapsed_seconds < 0:
                elapsed_seconds += 86400
                
            dynamic_effective_seconds = cached_effective_seconds + elapsed_seconds
            required_seconds = 27000 # 7.5 hours
            
            if dynamic_effective_seconds >= required_seconds:
                dynamic_remaining_seconds = 0
                logout_seconds = now_seconds
                self.title = f"✅ Keka: Done!"
                
                # Send a notification if we haven't already
                if not self.has_notified:
                    os.system('''osascript -e 'display notification "You have completed your 7.5 hours for today." with title "Keka Shift Complete! 🎉" sound name "Glass"' ''')

                    # Determine which audio to play based on language preference
                    language = os.environ.get("KEKA_LANGUAGE", "hindi").lower()
                    
                    if language != "none":
                        if language == "telugu":
                            mp3_filename = "Orey Ajaamu Lagettaroy.mp3"
                        else:
                            mp3_filename = "are_tu_jaa_re.mp3"
    
                        # Use absolute path and quotes to handle spaces in the filename
                        mp3_path = os.path.join(os.path.dirname(__file__), mp3_filename)
                        os.system(f"afplay '{mp3_path}' &")
                        
                    self.has_notified = True
            else:
                self.has_notified = False # reset if somehow they go back under
                dynamic_remaining_seconds = required_seconds - dynamic_effective_seconds
                logout_seconds = last_login_seconds + (required_seconds - cached_effective_seconds)
                if logout_seconds >= 86400:
                    logout_seconds -= 86400
                    
                self.title = f"⏳ {keka.format_hms(dynamic_remaining_seconds)} "
                
            # Update the dropdown menu with the specific details
            self.menu.clear()
            self.menu.add(rumps.MenuItem(f"Logged in at: {last_login}"))
            self.menu.add(rumps.MenuItem(f"Logout time: {keka.format_hms(logout_seconds)}"))
            self.menu.add(rumps.MenuItem(f"Effective so far: {keka.format_hms(dynamic_effective_seconds)}"))
            self.menu.add(rumps.separator)
            
            refresh_btn = rumps.MenuItem("Refresh from Server")
            refresh_btn.set_callback(self.manual_refresh)
            self.menu.add(refresh_btn)
            
            self.menu.add(rumps.MenuItem("Quit", callback=rumps.quit_application))
            
        except Exception as e:
            self.title = "Keka: Error"

    def manual_refresh(self, _):
        self.title = "Keka: Refreshing..."
        try:
            self.payload = keka.load_cached_or_fetch("refresh")
            self.update_clock(None)
        except Exception as e:
            self.title = "Keka: Auth Error"

def main():
    KekaStatusBarApp().run()

if __name__ == "__main__":
    main()
