#!/usr/bin/env python3
# Copyright (C) 2023 Stefy Lanza <stefy@nexlab.net> and SexHack.me
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import builtins
import logging
from logging.handlers import RotatingFileHandler
import configparser
import sys

import argparse
import os
import signal
import threading
import logging

import subprocess
import queue

# Read configuration
config = configparser.ConfigParser()
config.read('shmcamstudio.conf')


# Inter thread communication
qcore = queue.Queue() # IN -> core application (studio.py)
qobs  = queue.Queue() # IN -> OBS module
qweb  = queue.Queue() # IN -> Web Panel
qpnl  = queue.Queue() # IN -> tkinter panel

builtins.qcore = qcore
builtins.qobs = qobs
builtins.qweb = qweb
builtins.qpnl = qpnl
builtins.config = config

# Setup logging
log_file = config.get('General', 'log_file', fallback='/tmp/streaming_control.log')
log_level = config.get('General', 'log_level', fallback='INFO')

logging.basicConfig(
    level=getattr(logging, log_level),
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        RotatingFileHandler(log_file, maxBytes=1024*1024, backupCount=5),
        logging.StreamHandler(sys.stdout)
    ]
)
logger = logging.getLogger('SHMCamStudio')

builtins.logger = logger

builtins.TEMPLATE_DIR=os.path.join(os.path.dirname(__file__), 'templates')

from shmcs import run_command, check_port_available, create_daemon
from shmcs.webpanel import run_flask_app
from shmcs.panel import create_panel_gui
from shmcs.studio import run_camstudio
from shmcs.obs import run_obs_controller
from shmcs.browser import run_browser

def main():
    # Setup argument parser
    parser = argparse.ArgumentParser(description='Streaming Control Panel')
    parser.add_argument('--nogui', action='store_true', 
                        help='Do not start the graphical interface')
    parser.add_argument('--daemon', action='store_true', 
                        help='Run in daemon mode (Unix-like systems only, include --nogui)')
    parser.add_argument('--port', type=int, default=5000, 
                        help='Port for the web interface (default: 5000)')
    
    parser.add_argument('--browser', action="store_true",
                        help='launch local web browser')
    # Parse arguments
    args = parser.parse_args()

    try:
        # Start web interface in a background thread
        web_thread = threading.Thread(
            target=run_flask_app, 
            kwargs={'port': args.port},
            daemon=True
        )  
        web_thread.start()


        obs_thread = threading.Thread(
            target=run_obs_controller,
            kwargs={},
            daemon=True
        )
        obs_thread.start()

        if args.browser:
           browser_thread = threading.Thread(
             target=run_browser,
             kwargs={},
             daemon=True
           )
           logger.info("Browser launch requested")
           browser_thread.start()

        # Daemon mode for web interface
        if args.nogui or args.daemon:
            run_camstudio(args.daemon)
        else:
            core_thread = threading.Thread(
                target=run_camstudio,
                kwargs={},
                daemon=True
            )
            core_thread.start()

            # Launch Tkinter GUI
            window = create_panel_gui()
            window.mainloop()

    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
