from flask import current_app
from gitlab import Gitlab

from app.terraform.block.bridge_reachability import BlockBridgeReachabilityAutomation


class BlockBridgeGitlabAutomation(BlockBridgeReachabilityAutomation):
    """
    Automation task to import bridge reachability results from Gitlab.
    """

    short_name = "block_bridge_gitlab"
    description = "Import bridge reachability results from Gitlab"
    frequency = 30

    def fetch(self) -> None:
        self._lines = list()
        credentials = {"private_token": current_app.config['GITLAB_TOKEN']}
        if "GITLAB_URL" in current_app.config:
            credentials['url'] = current_app.config['GITLAB_URL']
        gitlab = Gitlab(**credentials)
        project = gitlab.projects.get(current_app.config['GITLAB_BRIDGE_PROJECT'])
        for vantage_point in current_app.config['GITHUB_BRIDGE_VANTAGE_POINTS']:
            contents = project.files.get(
                file_path=f"recentResult_{vantage_point}",
                ref=current_app.config["GITLAB_BRIDGE_BRANCH"]
            )
            # Decode the base64 first, then decode the UTF-8 string
            self._lines.extend(contents.decode().decode('utf-8').splitlines())
