from lib import config as config_module
from lib import logging as logging_lib
import requests
import stat
import os

config = config_module.config
log = logging_lib.log

def save_file_from_url(url, location, timeout=2000):
    """
    Downloads a file from the specified URL and saves it to the given location.
    Only proceeds if the web request status is 200 (OK). Includes a timeout.
    
    Parameters:
    - url (str): The URL of the file to download.
    - location (str): The file path where the downloaded file should be saved.
    - timeout (int): The timeout for the request in milliseconds. Default is 2000ms.
    
    Returns:
    - str: A message indicating the result of the operation.
    """
    try:
        # Convert timeout from milliseconds to seconds for the requests.get function
        timeout_seconds = timeout / 1000.0
        
        # Make the request to the given URL with the specified timeout
        response = requests.get(url, timeout=timeout_seconds)
        
        # Check if the request was successful (status code 200)
        if response.status_code == 200:
            # Open the specified location in binary write mode and write the content
            with open(location, 'wb') as f:
                f.write(response.content)
            if not os.access(location, os.X_OK):
                    current_permissions = stat.S_IMODE(os.lstat(location).st_mode)
                    os.chmod(location, current_permissions | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
            log.debug(f"Downloaded entrypoint {location}")
            return True
        else:
            return False
    except requests.Timeout:
        return False
    except Exception as e:
        log.debug(f"save_file_from_url() | An error occurred: {e}")
        return False

def cache_entrypoints(containers):
    try:
        entrypoint_files = os.listdir(config.entrypoints_folder)
        valid_conf = []
        for container in containers:
            if "name" in container and "custom_entrypoint" in container:
                file_name = f"{container["name"]}.sh"
                ok = False
                full_path = os.path.join(config.entrypoints_folder, file_name)
                if file_name in entrypoint_files:
                    ok=True
                    entrypoint_files.remove(file_name)
                else: # Download file
                    ok = save_file_from_url(container["custom_entrypoint"], full_path)
                valid_conf.append(ok)                
            else:
                valid_conf.append(True)
        for remaining_file in entrypoint_files: # We can remove files that are not needed anymore
            os.remove(os.path.join(config.entrypoints_folder,remaining_file))
        return valid_conf
    except Exception as e:
        return 'e'