from django.apps import AppConfig
from constance.apps import ConstanceConfig
from post_office.apps import PostOfficeConfig


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

    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()

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




def create_emails(sender=None, **kwargs):
    # Your specific logic here
    print("post post migrations")
    from post_office.models import EmailTemplate
    EmailTemplate.objects.update_or_create(
        name='generic',
        defaults={
        'subject'      :  'Neue Nachricht von gemeinschaffen.at',
        'description'  :  'Generic template',
        'html_content' :  "content html",
        'content'      :  "content"}
        )
    pass

class PostOfficeBase(PostOfficeConfig):


    def ready(self):

        # def db_table_exists(table_name):
        #     return table_name in connection.introspection.table_names()
        #
        # if db_table_exists(  'post_office_emailtemplate' ):
        #
        #     from post_office.models import EmailTemplate
        #     EmailTemplate.objects.update_or_create(
        #         name='generic',
        #         defaults={
        #         'subject'      :  'Neue Nachricht von gemeinschaffen.at',
        #         'description'  :  'Generic template',
        #         'html_content' :  "content html",
        #         'content'      :  "content"}
        #         )

        super().ready()

        post_migrate.connect(create_emails, sender=self)



#
#
# def db_table_exists(table_name):
#     return table_name in connection.introspection.table_names()
#
# if db_table_exists(  'post_office_emailtemplate' ):
#
#
#     tFile =  get_template('streets/email/generic.html')
#     with open( str(tFile.template.origin), 'r') as file:
#         tContentHTML = file.read()
#         tContent =  strip_tags(tContentHTML)
#
#     EmailTemplate.objects.update_or_create(
#         name='generic',
#         defaults={
#         'subject'      :  _('Message from pop-up.wien'),
#         'description'  :  'Generic template',
#         'html_content' :  tContentHTML,
#         'content'      :  tContent}
#         )
