from common.models import Config
from django.urls import reverse
from job_page.artifacts.views import get_config, get_artifact
from urllib.parse import urljoin

from .tank import TankAPICommunicator


def _construct_response(view, base_url, job, filenames):
    result = []
    for filename in filenames:
        relative_url = reverse(view, args=[job.id, filename])
        full_url = urljoin(base_url, relative_url)
        result.append({'filename': filename, 'url': full_url})
    return result


def get_artifacts_list(job, base_url):
    try:
        tank_api = TankAPICommunicator(job.id)
        filenames = tank_api.artifacts_list
    except ValueError:
        return []
    return _construct_response(get_artifact, base_url, job, filenames)


def get_configs_list(job, base_url):
    raw_configs = list(Config.objects.filter(job=job).values_list('name'))
    filenames = [raw_config[0] for raw_config in raw_configs]
    return _construct_response(get_config, base_url, job, filenames)
