import dj_database_url
import os

from django.utils.translation import gettext_lazy as _
from dotenv import load_dotenv


# Tap emus.conf if it's available
if os.path.exists("emus.conf"):
    load_dotenv("emus.conf")
elif os.path.exists("/etc/emus.conf"):
    load_dotenv("/etc/emus.conf")
elif os.path.exists("/usr/local/etc/emus.conf"):
    load_dotenv("/usr/local/etc/emus.conf")

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "l2-2d4dmvb0un0s)=5z%c87t*tg_hu&bt6*o^ks9r7f-3(mp$$"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django_extensions",
    "emus",
    "mathfilters",
    "search",
    "games",
    "rest_framework",
]

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

X_FRAME_OPTIONS = "SAMEORIGIN"

ROOT_URLCONF = "emus.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [str(BASE_DIR.joinpath("templates"))],  # new
        "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",
                "games.context_processors.game_systems",
            ],
        },
    },
]

WSGI_APPLICATION = "emus.wsgi.application"

DATABASES = {
    "default": dj_database_url.config(
        default=os.getenv("EMUS_DATABASE_URL", "sqlite:///db.sqlite3"), conn_max_age=600
    )
}


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
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = "static/"
STATIC_ROOT = os.getenv("EMUS_STATIC_ROOT", os.path.join(BASE_DIR, "static"))

MEDIA_URL = "/media/"
MEDIA_ROOT = os.getenv("EMUS_MEDIA_ROOT", os.path.join(BASE_DIR, "media"))
ROMS_DIR = os.path.join(MEDIA_ROOT, "roms")

SCRAPER_BIN_PATH = os.getenv("EMUS_SCRAPER_BINPATH", "Skyscraper")
SCRAPER_CONFIG_FILE = os.getenv("EMUS_SCRAPER_CONFIG_FILE", "skyscraper.ini")
SCRAPER_SITE = os.getenv("EMUS_SCRAPER_SITE", "screenscraper")

JSON_LOGGING = os.getenv("EMUS_JSON_LOGGING", False)
LOG_TYPE = "json" if JSON_LOGGING else "log"

RETROPIE_WEBRETRO_SYSTEM_MAP = {
    "n64": "mupen64plus_next",
    "nes": "nestopia",
    "megadrive": "genesis_plus_gx",
    "gba": "mgba",
    "snes": "snes9x",
}

RETROPIE_RETROARCH_WEB_SYSTEM_MAP = {
    "3do": "opera",
    "atarijaguar": "virtualjaguar",
    "coleco": "bluemsx",
    "dreamcast": "flycast",
    "gb": "gambatte",
    "gba": "mgba",
    "gbc": "gambatte",
    "gc": "dolphin",
    "megadrive": "genesis_plus_gx",
    "gamgear": "genesis_plus_gx",
    "atarilynx": "handy",
    "msx": "bluemsx",
    "n64": "mupen64plus_next",
    "nds": "desmume",
    "ngp": "fbneo",
    "ngpc": "fbneo",
    "nes": "nestopia",
    "pcengine": "mednafen_supergrafx",
    "psp": "ppsspp",
    "psx": "mednafen_psx",
    "saturn": "mednafen_saturn",
    "scummvm": "",
    "segacd": "genesis_plus_gx",
    "snes": "snes9x",
    "wii": "dolphin",
}

GAME_SYSTEM_SLUG_MAP = {
    "3do": "3DO",
    "atarijaguar": "Atari Jaguar",
    "coleco": "Colecovision",
    "dreamcast": "Dreamcast",
    "gb": "Game Boy",
    "gba": "Game Boy Advance",
    "gbc": "Game Boy Color",
    "gc": "GameCube",
    "megadrive": "Genesis/Mega Drive",
    "gamgear": "Game Gear",
    "atarilynx": "Atari Lynx",
    "msx": "MSX",
    "n64": "Nintendo 64",
    "nds": "Nintendo DS",
    "ngp": "Neo Geo Pocket",
    "neogeo": "Neo Geo",
    "ngpc": "Neo Geo Pocket Color",
    "nes": "Nintendo",
    "pcengine": "PC Engine/TurboGrafix 16",
    "psp": "Playstation Portable",
    "psx": "Playstation",
    "saturn": "Saturn",
    "scummvm": "ScummVM",
    "sega32x": "Sega 32X",
    "segacd": "Sega CD",
    "snes": "Super Nintendo",
    "wii": "Wii",
}

default_level = "INFO"
if DEBUG:
    default_level = "DEBUG"

LOG_LEVEL = os.getenv("EMUS_LOG_LEVEL", default_level)
LOG_FILE_PATH = os.getenv("EMUS_LOG_FILE_PATH", "/tmp/")

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "root": {"handlers": ["console", "file"], "level": LOG_LEVEL, "propagate": True},
    "formatters": {
        "color": {
            "()": "colorlog.ColoredFormatter",
            # \r returns caret to line beginning, in tests this eats the silly dot that removes
            # the beautiful alignment produced below
            "format": "\r"
            "{log_color}{levelname:8s}{reset} "
            "{bold_cyan}{name}{reset}:"
            "{fg_bold_red}{lineno}{reset} "
            "{thin_yellow}{funcName} "
            "{thin_white}{message}"
            "{reset}",
            "style": "{",
        },
        "log": {"format": "%(asctime)s %(levelname)s %(message)s"},
        "json": {
            "()": "pythonjsonlogger.jsonlogger.JsonFormatter",
            "format": "%(levelname)s %(name) %(funcName) %(lineno) %(asctime)s %(message)s",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "color",
            "level": LOG_LEVEL,
        },
        "null": {
            "class": "logging.NullHandler",
            "level": LOG_LEVEL,
        },
        "file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": "".join([LOG_FILE_PATH, "emus.", LOG_TYPE]),
            "formatter": LOG_TYPE,
            "level": LOG_LEVEL,
        },
        "requests_file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": "".join([LOG_FILE_PATH, "emus_requests.", LOG_TYPE]),
            "formatter": LOG_TYPE,
            "level": LOG_LEVEL,
        },
    },
    "loggers": {
        # Quiet down our console a little
        "django.channels.server": {
            "handlers": ["requests_file", "console"],
            "level": "ERROR",
            "propagate": False,
        },
        "django": {
            "handlers": ["file"],
            "propagate": True,
        },
        "daphne": {"handlers": ["file"], "propagate": False},
        "django.db.backends": {"handlers": ["null"]},
        "emus": {"handlers": ["console", "file"], "propagate": True},
    },
}

REMOVE_FROM_SLUGS = ["_", " ", "/"]

if DEBUG:
    # We clear out a db with lots of games all the time in dev
    DATA_UPLOAD_MAX_NUMBER_FIELDS = 3000
