import textwrap

import jinja2

from ..conf import Config

TEMPLATE = textwrap.dedent(
    """
    # This config was generated by 'mirror-tool gitlab-ci-yml'.
    # Use 'include' to load it from your main .gitlab-ci.yml.
    .mirror-tool-image:
      image:
        name: {{ image }}
        entrypoint: [""]
      tags: [docker]

    .mirror-tool-deploy:
      extends: .mirror-tool-image
      stage: {{ deploy_stage }}
      resource_group: mirror-tool

    "mirror-tool: validate config":
      extends: .mirror-tool-image
      script: mirror-tool validate-config
      rules:
      - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      - if: '$CI_PIPELINE_SOURCE == "push"'

    "mirror-tool: update":
      extends: .mirror-tool-deploy
      script: mirror-tool update
      rules:
      - if: '{{ token_var }} && $MANUAL_UPDATE == "1" && $CI_PIPELINE_SOURCE == "web" && $CI_COMMIT_BRANCH == "{{ update_branch }}"'
      - if: '{{ token_var }} && $CI_PIPELINE_SOURCE == "schedule" && $CI_COMMIT_BRANCH == "{{ update_branch }}"'

    {% if promote_src_branches %}
    "mirror-tool: promote":
      extends: .mirror-tool-deploy
      script: mirror-tool promote
      rules:
      - if: '{{ token_var }} && $MANUAL_PROMOTE == "1" && $CI_PIPELINE_SOURCE == "web"'
    {%- for branch in promote_src_branches %}
      - if: '{{ token_var }} && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "{{ branch }}"'
    {%- endfor %}
    {% endif %}
"""
)


def render_ci_template_from_args(**kwargs) -> str:
    env = jinja2.Environment()
    loader = jinja2.DictLoader({"template": TEMPLATE})
    return loader.load(env, "template").render(**kwargs)


def render_ci_template_from_config(conf: Config) -> str:
    kwargs = {
        # Not everything in here is actually configurable right now.
        # Some values extracted as args are things which I think might need to
        # become configurable later on.
        "image": "quay.io/rmcgover/mirror-tool:latest",
        "deploy_stage": "deploy",
        "token_var": conf.gitlab_merge.token,
        "update_branch": conf.gitlab_merge.dest,
        "promote_src_branches": [p.src for p in conf.gitlab_promote],
    }
    return render_ci_template_from_args(**kwargs)
