"""
Django settings for TorinoMeteo project.

Generated by 'django-admin startproject' using Django 1.8.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from dotenv import load_dotenv
from getenv import env


def here(*x):
    return os.path.join(
        os.path.dirname(os.path.realpath(__file__)), *x
    )

BASE_DIR = os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)

dotenv_path = here('..', '..', '.env')
load_dotenv(dotenv_path)

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env(
    'SECRET_KEY',
    '49saa%ruey1&!nveiz*f(cu$)0pje8wz7u++y-0ljd2)9r)j8h'
)

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

ALLOWED_HOSTS = []

ADMINS = (
    ('abidibo', 'web.sites.logs@gmail.com'),
)

# VCO
VCO_USER = env('VCO_USER')
VCO_PWD = env('VCO_PWD')

# SITE
SITE_ID = 1
HTTPS = False
CRONTAB_KEY = env('CRONTAB_KEY', 'crontabkey')

# MAIL
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
NOREPLY_EMAIL = 'noreply@torinometeo.org'
NET_REQUEST_EMAIL = 'info@torinometeo.org'
DEFAULT_FROM_EMAIL = 'noreply@torinometeo.org'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': env('DB_NAME', 'dbtorinometeo'),
        'HOST': env('DB_HOST', 'localhost'),
        'USER': env('DB_USER', 'torinometeo'),
        'PASSWORD': env('DB_PASSWORD', required=True),
        'PORT': '',
        'OPTIONS': {
            'init_command': 'SET default_storage_engine=InnoDB',
        }
    }
}

# Application definition

INSTALLED_APPS = (
    'core',
    'baton',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.flatpages',
    'ckeditor',
    'ckeditor_uploader',
    'widget_tweaks',
    'pipeline',
    'corsheaders',
    'constance',
    'constance.backends.database',
    'filer',
    'mptt',
    'easy_thumbnails',
    'django_cleanup',
    'captcha',
    'sorl.thumbnail',
    'disqus',
    'taggit',
    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_swagger',
    'treenav',
    'social_django',
    'social_auth', # wrapper
    'colorful',
    # tm
    'forecast',
    'realtime',
    'blog',
    'webcam',
    'bookmarks',
    'baton.autodiscover',
)

MIDDLEWARE = (
    'corsheaders.middleware.CorsMiddleware',
    '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',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)

ROOT_URLCONF = 'core.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug': False,
            'context_processors': [
                'constance.context_processors.config',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'core.context_processors.debug',
                'treenav.context_processors.treenav_active',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'core.wsgi.application'

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'it-it'

TIME_ZONE = 'Europe/Rome'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# CONSTANCE
CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
CONSTANCE_CONFIG = {
    'RADAR_BASE_URL': ('http://www.meteosvizzera.admin.ch/product/output/radar/precipitation/', 'Base URL immagini radar'),
}

CONSTANCE_CONFIG_FIELDSETS = {
    'Realtime': ('RADAR_BASE_URL', ),
}


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

STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'pipeline.finders.PipelineFinder',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# Uploaded files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_FORECAST_IMG_REL = 'forecast/img'
MEDIA_REALTIME_STATION_IMG_REL = 'realtime/station/img'
MEDIA_REALTIME_NET_REQUEST_IMG_REL = 'realtime/net_request/img'
MEDIA_BLOG_IMG_REL = 'blog/img'
MEDIA_WEBCAM_IMG_REL = 'webcam/img'

# DRF
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

SWAGGER_SETTINGS = {
    'USE_SESSION_AUTH': False,
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'name': 'Authorization',  # set 'Token token-hash' in authorize
            'in': 'header'
        }
    },
    'JSON_EDITOR': True
}

# CORS HEADERS
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

# TAGGIT
TAGGIT_CASE_INSENSITIVE = True

# ADMIN
BATON = {
    'SITE_HEADER': '<img src="/static/core/src/img/logoTM.png" style="height: 50px;"/>',
    'SITE_TITLE': 'TorinoMeteo',
    'INDEX_TITLE': 'Amministrazione Sito',
    'CHANGELIST_FILTERS_IN_MODAL': True,
    'LOGIN_SPLASH': '/static/core/src/img/bg.jpg',
    'MENU': (
        {'type': 'title', 'label': 'Sistema',  'apps': ('auth', 'sites', 'constance', )},
        {'type': 'app', 'name': 'auth', 'label': 'Autenticazione', 'icon':'fa fa-lock'},
        {'type': 'model', 'app': 'authtoken', 'name': 'token', 'label': 'REST token', 'icon':'fa fa-key'},
        {'type': 'model', 'app': 'sites', 'name': 'site', 'label': 'Siti', 'icon':'fa fa-leaf'},
        {'type': 'model', 'app': 'constance', 'name': 'config', 'label': 'Impostazioni', 'icon':'fa fa-cogs'},

        
        {'type': 'title', 'label': 'Risorse',  'apps': ('filer', )},
        {'type': 'model', 'app': 'filer', 'name': 'folder', 'label': 'File manager', 'icon':'fa fa-folder-open'},
        

        {'type': 'title', 'label': 'Navigazione',  'apps': ('treenav', )},
        {'type': 'model', 'app': 'treenav', 'name': 'menuitem', 'label': 'Menu', 'icon':'fa fa-bars'},

        {'type': 'title', 'label': 'Contenuti',  'apps': ('flatpages', 'blog', )},
        {'type': 'model', 'app': 'flatpages', 'name': 'flatpage', 'label': 'Pagine', 'icon':'fa fa-file-alt'},
        {'type': 'model', 'app': 'blog', 'name': 'entry', 'label': 'Blog', 'icon':'fa fa-book'},

        {'type': 'title', 'label': 'Meteo',  'apps': ('realtime', 'webcam', 'forecast', )},
        {'type': 'app', 'name': 'realtime', 'label': 'Realtime', 'icon':'fa fa-clock'},
        {'type': 'app', 'name': 'forecast', 'label': 'Previsioni', 'icon':'fa fa-cloud-sun-rain'},
        {'type': 'model', 'app': 'webcam', 'name': 'webcam', 'label': 'Webcam', 'icon':'fa fa-camera'},

        {'type': 'title', 'label': 'Preferiti',  'apps': ('bookmarks', )},
        {'type': 'model', 'app': 'bookmarks', 'name': 'stationbookmark', 'label': 'Stazioni', 'icon':'fa fa-bookmark'},
    ),
    'COPYRIGHT': '© 2019 torinometeo.org',
    'SUPPORT_HREF': 'mailto:abidibo@gmail.com',
    'POWERED_BY': '<a href="https://www.abidibo.net">abidibo</a>',
    'ANALYTICS': {
        'CREDENTIALS': os.path.join(BASE_DIR, 'credentials.json') if DEBUG else os.path.join(BASE_DIR, '..', '..', 'credentials.json'),
        'VIEW_ID': '34377537',
    }
}

# CKEDITOR
CKEDITOR_UPLOAD_PATH = 'ckeditor/'
CKEDITOR_JQUERY_URL = ''
CKEDITOR_IMAGE_BACKEND = 'pillow'
CKEDITOR_CONFIGS = {
    'default': {
        'skin': 'moono',
        'toolbar_Basic': [
                ['Source', '-', 'Bold', 'Italic']
        ],
        'toolbar_Full': [
            ['Styles', 'Format', 'Bold', 'Italic', 'Underline',
                'Strike', 'SpellChecker', 'Undo', 'Redo'],
            ['NumberedList', 'BulletedList'],
            ['Link', 'Unlink', 'Anchor'],
            ['Image', 'Flash', 'Table', 'HorizontalRule'],
            ['TextColor', 'BGColor'],
            ['SpecialChar'], ['PasteFromWord'], ['Source']
        ],
        'toolbar': 'Full',
        'height': 291,
        'width': 835,
        'filebrowserWindowWidth': 940,
        'filebrowserWindowHeight': 725,
        'removePlugins': 'stylesheetparser',
        'allowedContent': True,
        'extraAllowedContent': 'iframe[*]',
        'stylesSet': 'core_styles:/static/core/src/js/ckeditor_styles.js',
    }
}

# pipeline
PIPELINE = {
    'STYLESHEETS': {
        'vendor': {
            'source_filenames': (
                'core/src/vendor/Font-Awesome/scss/font-awesome.scss',
                'core/src/vendor/bootstrap-datetimepicker/bootstrap-datetimepicker.min.css', # noqa
                'core/src/vendor/magnific-popup/magnific-popup.css',
            ),
            'output_filename': 'core/css/vendor.min.css',
        },
        'torinometeo': {  # bootstrap + custom
            'source_filenames': (
                'core/src/scss/styles.scss',
                'social_auth/scss/_style.scss'
            ),
            'output_filename': 'core/css/core.min.css',
        },
        'api': {  # api
            'source_filenames': (
                'core/src/scss/api/styles.scss',
            ),
            'output_filename': 'core/css/api.min.css',
        },
    },
    'JAVASCRIPT': {
        'vendor': {
            'source_filenames': (
                'core/src/vendor/popper/popper.min.js', # noqa
                'core/src/vendor/bootstrap/js/tether.js',
                'core/src/vendor/bootstrap/js/bootstrap.min.js',
                'core/src/vendor/moment/moment-with-locales.min.js',
                'core/src/vendor/bootstrap-material-design/scripts/ripples.js',
                'core/src/vendor/bootstrap-material-design/scripts/material.js',
                'core/src/vendor/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js', # noqa
                'core/src/vendor/magnific-popup/magnific-popup.min.js',
            ),
            'output_filename': 'core/js/vendor.min.js'
        },
        'torinometeo': {
            'source_filenames': (
                'core/src/js/core.js',
                'core/src/js/realtime_jumbotron.js',
            ),
            'output_filename': 'core/js/core.min.js'
        },
    },
    'COMPILERS': ('pipeline.compilers.sass.SASSCompiler', ),
    'CSS_COMPRESSOR': None,
    'JS_COMPRESSOR': None,
}

# Disqus
DISQUS_API_KEY = 'kjNmaqKMTwg388VnEJicaYV1jdteFZYQLQcsvQwmQJth4V2LpW9lJ3sfgSsxN4YP' # noqa
DISQUS_WEBSITE_SHORTNAME = 'torinometeo'

THUMBNAIL_HIGH_RESOLUTION = True
THUMBNAIL_REMOVE_URL_ARGS = False
THUMBNAIL_PROCESSORS = (
    'easy_thumbnails.processors.colorspace',
    'easy_thumbnails.processors.autocrop',
    # 'easy_thumbnails.processors.scale_and_crop',
    'filer.thumbnail_processors.scale_and_crop_with_subject_location',
    'easy_thumbnails.processors.filters',
)

# SOCIAL AUTH

USERS_GROUP_NAME = 'users' # group associated to new registrations

SOCIAL_AUTH_FORCE_EMAIL_VALIDATION = False

# action query string param traduced into alert, like
# Hey you son of a bitch, in order to do this you must be authenticated
SOCIAL_AUTH_ACTION_BOOKMARK = 'Devi essere loggato per salvare un preferito'

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
LOGIN_URL = '/#login'
LOGIN_ERROR_URL = '/account/errors/'
# SOCIAL_AUTH_EMAIL_VALIDATION_URL = '/account/email-sent/'


AUTHENTICATION_BACKENDS = (
    'social_core.backends.open_id.OpenIdAuth',
    'social_core.backends.google.GoogleOpenId',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.google.GoogleOAuth',
    'social_core.backends.facebook.FacebookOAuth2',
    'social_core.backends.email.EmailAuth',
    'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_PIPELINE = (

    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_auth.pipeline.require_email',  # cut the pipeline to check if email is present
    'social_core.pipeline.social_auth.associate_by_email',
    'social_core.pipeline.user.create_user',
    'social_auth.pipeline.set_password',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
)


SOCIAL_AUTH_EMAIL_FORM_URL = '/account/login/email/'
SOCIAL_AUTH_EMAIL_FORM_HTML = 'social_auth/registration.html'

# SOCIAL_AUTH_EMAIL_VALIDATION_FUNCTION = 'social_auth.pipeline.email_validation'

# Apixu
APIXU_KEY = 'e683d070df0348fea6393603173010'

# yr
BASE_WEATHER_ICON_URL = 'https://www.torinometeo.org/static/weathericons/'

# twitter
SOCIAL_AUTH_TWITTER_KEY = 'HRDVxN1i59Aw6VEr3Pco83Sss'
SOCIAL_AUTH_TWITTER_SECRET = 'dXaUYYFMQs1MvYySpSjXkxGIXR6csGXNR7QnTRw9T9M2C6FV7C'

# facebook
SOCIAL_AUTH_FACEBOOK_SECRET = 'a784e278078f8102e536484de36e03e2'
SOCIAL_AUTH_FACEBOOK_KEY = '133317480065442'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email',]
#http://stackoverflow.com/questions/32024327/facebook-doesnt-return-email-python-social-auth
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
    'fields': 'id,name,email',
}

# google
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '128805411620-q30fpveccb2qrr4rpopvlccbnlvsgkml.apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '3bcdRfz4DmoNRHM8H7jsQw4I'

EMAIL_FROM = 'noreply@torinometeo.org'

# LOGGING

LOGGING_DEFAULT = {
    'handlers': ['console', 'file'],
    'level': 'DEBUG',
    'propagate': True,
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' #  noqa
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
        #  configure the log to be rotated daily
        #  see
        #  noqa https://docs.python.org/2.7/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler
        'file': {
            'level': 'INFO',
            'formatter': 'verbose',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': here('..',
                             '..',
                             '..',
                             os.path.join('logs', 'debug.log')
                             ),
            'when':     'midnight',
        },
        'celery_logger': {
            'level': 'ERROR',
            'filters': None,
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': here('..', '..', '..',
                             os.path.join('logs', 'celery.log')),
            'formatter': 'verbose',
            'when':     'midnight',
        },
        'realtime_celery_logger': {
            'level': 'DEBUG',
            'filters': None,
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': here('..', '..', '..',
                             os.path.join('logs', 'realtime.log')),
            'formatter': 'verbose',
            'when':     'midnight',
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['mail_admins', 'console', 'file', ],
            'level': 'ERROR',
            'propagate': False,
        },
        # noqa http://stackoverflow.com/questions/7768027/turn-off-sql-logging-while-keeping-settings-debug
       'django.db.backends': {
            'handlers': ['null'],  # Quiet by default!
            'propagate': False,
            'level': 'DEBUG',
        },
        'celery': {
            'handlers': ['celery_logger'],
            'level': 'ERROR',
            'propagate': True,
        },
        'celery.tasks': {
            'handlers': ['mail_admins', 'celery_logger'],
            'level': 'ERROR',
            'propagate': True,
        },
        'realtime.tasks': {
            'handlers': ['realtime_celery_logger', ],
            'level': 'DEBUG',
            'propagate': False,
        },
        'core': LOGGING_DEFAULT,
        '': LOGGING_DEFAULT,  # root logger
    },
}
