from django.apps import AppConfig
from constance.apps import ConstanceConfig
from post_office.apps import PostOfficeConfig
from django.contrib.auth.apps import AuthConfig


from django.db import connection
from django.db.models.signals import post_migrate

from django.template.loader import render_to_string, get_template
from django.utils.html import strip_tags


class ConstanceBase(ConstanceConfig):
    verbose_name = "Configuration"


def create_admin(sender=None, **kwargs):

    from django.contrib.auth.models import User
    from django.contrib.auth.models import Group

    user = User.objects.update_or_create(username='admin',
                            defaults={
                             'email':'admin@server.com',
                             'password':'admin_pass',
                             'is_superuser': 'True',
                             'is_staff': 'True' }
                             )
    u = User.objects.get(username='admin')
    u.set_password('admin_pass')
    u.save()

    Group.objects.update_or_create(name='submission')
    Group.objects.update_or_create(name='jury')


class project_base(AppConfig):
    name = 'project_base'
    def ready(self):
        # print("base ready")
        super().ready()
        post_migrate.connect(create_admin, sender=self)


class AuthConfigBase(AuthConfig):

    def ready(self):
        # print("base ready")
        super().ready()
        post_migrate.connect(create_admin, sender=self)

content_html = """
<table><tbody><tr><td><h2>&nbsp;gemeinschaffen.com </h2></td></tr><tr><td><h3>name</h3><p>{{product_name}}</p><h3>claim</h3><p>{{product_claim}}</p><h3>beschreibung</h3><p>{{product_beschreibung}}</p><h3>learning</h3><p>{{product_learning}}</p><h3>status</h3><p>{{product_status}}</p><h3>adresse</h3><p>{{product_adresse}}</p><h3>plz</h3><p>{{product_plz}}</p><h3>adresse_zusatz</h3><p>{{product_adresse_zusatz}}</p><h3>ort</h3><p>{{product_ort}}</p><h3>website</h3><p>{{product_website}}</p><h3>email</h3><p>{{product_email}}</p></td></tr><tr><td>&nbsp;<a href="https://gemeinschaffen.com/mab/products/">gemeinschaffen.com</a></td></tr></tbody></table><p>&nbsp;</p>
"""

content_txt = strip_tags(content_html)

def create_emails(sender=None, **kwargs):
    from post_office.models import EmailTemplate
    EmailTemplate.objects.update_or_create(
        name='generic',
        defaults={
        'subject'      :  'Neue Nachricht von gemeinschaffen.com',
        'description'  :  'Generic template',
        'html_content' :  content_html,
        'content'      :  content_txt}
        )
    pass


class PostOfficeBase(PostOfficeConfig):

    def ready(self):
        super().ready()
        post_migrate.connect(create_emails, sender=self)
