from typing import Any

from flask import current_app

from app.terraform.list import ListAutomation


class ListGitlabAutomation(ListAutomation):
    short_name = "list_gitlab"
    description = "Update mirror lists in GitLab repositories"
    provider = "gitlab"
    always_refresh = True

    template_parameters = [
        "gitlab_token",
        "gitlab_author_email",
        "gitlab_author_name",
        "gitlab_commit_message"
    ]

    template = """
    terraform {
      {{ backend_config }}
      required_providers {
        gitlab = {
          source = "gitlabhq/gitlab"
          version = "~> 3.14.0"
        }
      }
    }

    provider "gitlab" {
      {% if gitlab_url %}
      base_url = "{{ gitlab_url }}/api/v4/"
      {% endif %}
      token = "{{ gitlab_token }}"
    }

    {% for list in lists %}
    data "gitlab_project" "project_{{ list.id }}" {
      id = "{{ list.container }}"
    }

    resource "gitlab_repository_file" "file_{{ list.id }}" {
      project        = data.gitlab_project.project_{{ list.id }}.id
      file_path      = "{{ list.filename }}"
      branch         = "{{ list.branch }}"
      content        = base64encode(file("{{ list.format }}.{{ list.pool.pool_name }}.{{ list.encoding }}"))
      author_email   = "{{ gitlab_author_email }}"
      author_name    = "{{ gitlab_author_name }}"
      commit_message = "{{ gitlab_commit_message }}"
    }

    {% endfor %}
    """

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        if 'GITLAB_URL' in current_app.config:
            self.template_parameters.append("gitlab_url")
