import requests

from ...Machine.MachineInterface import MachineInterface
from ..Playbooks.Playbook import PlaybookCredentialCollection, FileCleanupTask
from ... import Configuration
from ...Logging.Logger import log, Severity
from ..SetupStep import SetupStep
from requests.auth import HTTPBasicAuth


class DownloadCustomerFile(SetupStep):
    def __init__(self, source_filename: str, target_filename: str, machine: MachineInterface, keep_file=False):
        super().__init__()
        self.source_filename = source_filename
        self.target_filename = target_filename
        self.machine = machine
        self.keep_file = keep_file

    def run(self, file_cleanup_stack : list[FileCleanupTask], credentials: PlaybookCredentialCollection) -> bool:
        basic = HTTPBasicAuth(credentials.mli, credentials.mli_password)
        url = f'https://{Configuration.get_val("repository", "server")}/customers/{credentials.mli}/{self.source_filename}'
        response = requests.get(url, auth=basic)
        if response.status_code == 200:
            log(f"File downloaded", Severity.DEBUG)
            self.machine.write_file(self.target_filename, response.content)

            if not self.keep_file:
                file_cleanup_stack.append(FileCleanupTask(self.machine, self.target_filename))

            log("Content saved to target.", Severity.DEBUG)
            return True
        else:
            log(f"Unable to download file - Status code: {response.status_code}", Severity.ERROR)
            return False