from app import app
from app.models.base import Group
from app.terraform import BaseAutomation


class EotkAutomation(BaseAutomation):
    short_name = "eotk"

    template_parameters = [
        "aws_access_key",
        "aws_secret_key"
    ]

    template = """
    terraform {
      required_providers {
        aws = {
          version = "~> 4.4.0"
        }
      }
    }
    
    provider "aws" {
      access_key = "{{ aws_access_key }}"
      secret_key = "{{ aws_secret_key }}"
      region = "us-east-2"
    }
    
    provider "aws" {
      access_key = "{{ aws_access_key }}"
      secret_key = "{{ aws_secret_key }}"
      region = "eu-central-1"
      alias = "second_region"
    }
    
    {% for group in groups %}
    module "eotk_{{ group.id }}" {
      providers = {
        aws = aws,
        aws.second_region = aws.second_region
      }
      source = "sr2c/eotk/aws"
      version = "0.0.2"
      namespace = "{{ global_namespace }}"
      tenant = "{{ group.group_name }}"
      name = "eotk"
      label_order = ["namespace", "tenant", "name", "attributes"]
      disable_api_termination = true
    }
    {% endfor %}
    """

    def generate_terraform(self):
        self.write_terraform_config(
            self.template,
            groups=Group.query.filter(Group.eotk == True).all(),
            global_namespace=app.config['GLOBAL_NAMESPACE'],
            **{
                k: app.config[k.upper()]
                for k in self.template_parameters
            }
        )


if __name__ == "__main__":
    with app.app_context():
        auto = EotkAutomation()
        auto.generate_terraform()
        auto.terraform_init()
        auto.terraform_apply()
