import os
import subprocess
import sys

import logging
logger = logging.getLogger(__name__)

def newVersionAvailable() -> bool:
    '''
    Check if a newer version of millconnect is available.

    Returns:
        bool: True if a newer version is available, False otherwise.

    Note:
        This function uses the 'pip list --outdated' command to check for outdated packages.
    '''
    process_output = ''
    try:
        process_output = subprocess.check_output([sys.executable, '-m', 'pip', 'list','--outdated'])
    except subprocess.CalledProcessError as pip_exec:
        if pip_exec.returncode == 120:
            process_output = pip_exec.output
        else:
            raise
        
    logger.debug('Outdated packages:\n%s', process_output.decode())
    outdated_packages = [r.decode().split('==')[0] for r in process_output.split()]
    return 'millconnect' in outdated_packages

def restartIntoNewApplication():
    '''
    Restart the newly downloaded application with the same arguments.

    Note:
        This function uses 'os.execv' to execute a new instance of the current script.
    '''
    args = [sys.executable, '-m', 'millconnect.gui']
    if len(sys.argv) > 1:
        args += sys.argv[1:]

    for i, arg in enumerate(args):
        args[i] = f'"{arg}"'
    
    logger.info(f'Re-spawning: {sys.executable} {args}')
    os.execv(sys.executable, args)

def update():
    '''
    Updates this application if a new version is available and restarts into it.

    Note:
        This function uses 'subprocess.check_call' to install the updated package.
    '''
    logger.info('Updating...')
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'millconnect'])
    restartIntoNewApplication()