import os
from pathlib import Path

from django.conf import settings
from django.core.management.base import BaseCommand
from django.template import Template, Context

ELK_URL = getattr(settings, 'ELASTIC_URL', 'localhost:9200')
ELK_LOGIN = getattr(settings, 'ELK_LOGIN', 'elastic')
ELK_PASS = getattr(settings, 'ELK_PASS', 'changeme')
VECTOR_CONFIG_DIR = getattr(settings, 'LOGSTASH_CONFIG_DIR')


class Command(BaseCommand):
    help = 'Load default Vector configs'

    def handle(self, *args, **options):
        templates_path = Path(os.path.abspath(__file__)).parents[0] / 'templates'
        context = Context({
            "elastic_url": ELK_URL,
            "elastic_login": ELK_LOGIN,
            "elastic_password": ELK_PASS,
        })
        Path(VECTOR_CONFIG_DIR).mkdir(exist_ok=True)

        for template in os.listdir(templates_path):
            with open(f"{templates_path}/{template}", 'r') as template_file:
                template_text = template_file.read()
            config_content = Template(template_text).render(context)
            with open(os.path.join(VECTOR_CONFIG_DIR, template), 'w') as f:
                f.write(config_content)
                print(f'Created {template}')
