import os
from django.core.management.base import BaseCommand
from Multitenancy import settings

from mtDjango.models import Tenant, Tenant_Domain
from sys import stdin


class Command(BaseCommand):
    help = 'Create a tenant'
    args = 'no arguments here'

    def handle(self, *args, **options):
        create_tenant(self)


def create_tenant(self, testing):

    if testing:
        input_correct = True
        name = 'TestTenant'
        email = 'ttenant@mtd.de'
        active = 'y'
        domain = 'localhost'
    else:
        input_correct = False
        name = None
        email = None
        active = None
        domain = None
    while not input_correct:
        if email is not None and len(email) > 7 and email.__contains__("@") and email.__contains__("."):
            if name is not None and len(name) > 0:

                if active is not None and active == 'y' or active == 'n':
                    if domain is not None and len(domain) > 4:
                        input_correct = True
                    else:
                        if domain is not None:
                            self.stdout.write("Entered domain name ist to short")
                        self.stdout.write("Domain name: ")
                        domain = stdin.readline()[:-1]
                else:
                    if active is not None:
                        self.stdout.write("Is the tenant active?.")
                    self.stdout.write("Is active (y/n): ")
                    active = stdin.readline()[:-1]
            else:
                if name is not None:
                    self.stdout.write("No name entered.")
                self.stdout.write("Name: ")
                name = stdin.readline()[:-1]

        else:
            if email is not None:
                self.stdout.write("No Valid email address entered.\n")
            self.stdout.write("Email:")
            email = stdin.readline()[:-1]
    tenant = Tenant.objects.create(name=name, email=email, active=active == "y")
    tenant.save()
    Tenant_Domain.objects.create(name=domain, tenant=tenant)
    data_dir = str(os.path.dirname(settings.TENANT_DIR)) + os.sep + str(tenant.id) + os.sep

    temp_dir = data_dir + 'templates'
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)

    temp_dir = data_dir + 'static'
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)

    temp_dir = data_dir + 'media'
    if not os.path.exists(temp_dir):
        os.makedirs(temp_dir)

    mtpython_dir = data_dir + 'mtpython'
    if not os.path.exists(mtpython_dir):
        os.makedirs(mtpython_dir)

    self.stdout.write("Tenant successful created.")