import environ
import os
from urllib.parse import urljoin

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, True),
    MYSQL_HOST=(str, "mysql"),
    MYSQL_PORT=(int, 3306),
    MYSQL_DATABASE=(str, "fet2020db"),
    MYSQL_USER=(str),
    MYSQL_PASSWORD=(str),
    HOST_NAME=(str, "localhost"),
    ETHERPAD_PORT=(str, "9001"),
    ETHERPAD_HOST=(str, ""),
    ETHERPAD_GROUP=(str, ""),
    GALLERY_PATH=(str, "uploads/gallery"),
)

# Prints and logs are written to console
# TODO: Change before release
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
}


# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env("DEBUG")
if DEBUG:
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = "r37-i7l)vrduzz2-gira+z#u!p!di9#f+%s*5-bb($hg)55@ns"
else:
    SECRET_KEY = env("SECRET_KEY")


# HOST
ALLOWED_HOSTS = ["127.0.0.1", env("HOST_NAME"), "fet.at"]
HOST_NAME = env("HOST_NAME")


DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 * 1024


INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.admindocs",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    "django.contrib.sitemaps",
    "django.contrib.flatpages",

    "taggit",
    "ckeditor",
    "ckeditor_uploader",
    "easy_thumbnails",
    "rest_framework",
    "softhyphen",
    "django_crontab",
    "django_filters",
    "django_static_jquery_ui",
    "fontawesomefree",

    "core.apps.CoreConfig",
    "posts.apps.PostsConfig",
    "members.apps.MembersConfig",
    "documents.apps.DocumentsConfig",
    "blackboard.apps.BlackboardConfig",
    "tasks.apps.TasksConfig",
    "gallery.apps.GalleryConfig",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "fet2020.middleware.FETHeaderMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware",
]

ROOT_URLCONF = "fet2020.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "templates"),
        ],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "django.template.context_processors.i18n",
            ],
        },
    },
]

WSGI_APPLICATION = "fet2020.wsgi.application"


# Database
if DEBUG:
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
        }
    }
else:
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.mysql",
            "NAME": env("MYSQL_DATABASE"),
            "USER": env("MYSQL_USER"),
            "PASSWORD": env("MYSQL_PASSWORD"),
            "HOST": env("MYSQL_HOST"),
            "PORT": env("MYSQL_PORT"),
        }
    }


AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
]


# Password validation
AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
LANGUAGE_CODE = "de-at"
TIME_ZONE = "CET"
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")]


# Sites
SITE_ID = 1


# Static files (CSS, JavaScript, Images)
if DEBUG:
    STATIC_URL = "/static/"
else:
    STATIC_URL = "/assets/"

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "gallery/static"),    
    os.path.join(BASE_DIR, "static"),
]

STATIC_ROOT = "assets/"
MEDIA_ROOT = os.path.join(BASE_DIR, "files/")
MEDIA_URL = "/files/"


# TAGGIT
TAGGIT_FORCE_LOWERCASE = True


#CKEDITOR
CKEDITOR_UPLOAD_PATH = "upload"

CKEDITOR_CONFIGS = {
    "default": {
        "stylesSet": [
            {
                "name": "Überschrift 2",
                "element": "h2",
                "attributes": {},
            },
            {
                "name": "Code",
                "element": "code",
                "attributes": {"class": "code-block"},
            },
        ],
        "toolbar": "Custom",
        "toolbar_Custom": [
            {"name": "styles", "items": ["Styles", "Format", "Font", "FontSize"]},
            {"name": "tools", "items": ["Maximize", "ShowBlocks"]},
            {"name": "document", "items": ["Source"]},
            "/",
            {
                "name": "basicstyles",
                "items": [
                    "Bold",
                    "Italic",
                    "Underline",
                    "Strike",
                    "Subscript",
                    "Superscript",
                    "-",
                    "RemoveFormat",
                ],
            },
            {
                "name": "paragraph",
                "items": [
                    "NumberedList",
                    "BulletedList",
                    "-",
                    "Outdent",
                    "Indent",
                    "-",
                    "Blockquote",
                    "CreateDiv",
                    "-",
                    "JustifyLeft",
                    "JustifyCenter",
                    "JustifyRight",
                    "JustifyBlock",
                ],
            },
            {"name": "links", "items": ["Link", "Unlink", "Anchor"]},
            {
                "name": "insert",
                "items": [
                    "Image",
                    "Flash",
                    "Table",
                    "HorizontalRule",
                    "Smiley",
                    "SpecialChar",
                ],
            },
        ],
    }
}


# THUMBNAIL
THUMBNAIL_ALIASES = {
    "": {
        "avatar": {"size": (50, 50), "crop": True},
        "thumb": {"size": (150, 150), "crop": True},
        "portrait": {"size": (200, 300), "crop": False},
    },
}


# ETHERPAD HOST
ETHERPAD_HOST = env("ETHERPAD_HOST").strip()
if not ETHERPAD_HOST or ETHERPAD_HOST == "":
    ETHERPAD_HOST = urljoin("https://" + env("HOST_NAME"), "etherpad/")

# ETHERPAD CLIENT
if DEBUG:
    ETHERPAD_CLIENT = {
        "url": "http://etherpad:" + env("ETHERPAD_PORT"),
        "exturl": ETHERPAD_HOST,
        "apikey": "/srv/etherpad/APIKEY.txt",
        "group": env("ETHERPAD_GROUP"),
    }
else:
    ETHERPAD_CLIENT = {
        "url": "http://etherpad:" + env("ETHERPAD_PORT"),
        "exturl": urljoin("https://" + env("HOST_NAME"), "etherpad/"),
        "apikey": "/app/etherpad/APIKEY.txt",
        "group": env("ETHERPAD_GROUP"),
    }


# REST FRAMEWORK
REST_FRAMEWORK = {
    "DEFAULT_PERMISSION_CLASSES_CLASSES": [
        "rest_framework.permissions.AllowAny",
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": (),
}


# DJANGO MAIL
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "buran.htu.tuwien.ac.at"
EMAIL_PORT = 587
EMAIL_USE_TLS = True


# CRON JOBS
CRONJOBS = [
    ("0 16 * * *", "posts.cronjobs.check_to_send_agenda_mail"),
]


# AUTHENTICATIONS
LOGIN_URL = "/auth/login"


# MIGRATION FROM DJANGO 3.1 TO DJANGO 3.2
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"


# GALLERY
GALLERY = {
    "path": env("GALLERY_PATH"),
    "thumb_path": env("GALLERY_PATH") + "_thumb",
}

# MIGRATION TO DJANGO 4.0
CSRF_TRUSTED_ORIGINS = [
    "https://" + env("HOST_NAME"),
]
