"""
Django settings for src project.

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

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
import dj_database_url
import datetime
from django.utils.translation import ugettext_lazy as _

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

# 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 = os.environ.get('DJANGO_SECRET_KEY')
if not SECRET_KEY:
    raise ValueError('Secret key does not set')

INSTALLED_APPS = (
    'aparnik',
    'aparnik.contrib.suit',
    'debug_toolbar',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'jalali_date',  # required for admin jalali date
    'rest_framework',
    'fcm_django',
    'dynamic_raw_id',
    'django_filters',
    'ckeditor',
    'ckeditor_uploader',
    'tagulous',
    'colorfield',
    # This applications
    'rangefilter',
    'import_export',
    'channels',

    'aparnik.contrib.province',
    'aparnik.contrib.users',
    'aparnik.contrib.audits',
    'aparnik.contrib.addresses',
    'aparnik.contrib.bankaccounts',
    'aparnik.contrib.managements',
    'aparnik.contrib.aboutus',
    'aparnik.contrib.contactus',
    'aparnik.contrib.invitation',
    'aparnik.contrib.basemodels',
    'aparnik.contrib.filefields',
    'aparnik.contrib.bookmarks',
    'aparnik.contrib.reviews',
    'aparnik.contrib.questionanswers',
    'aparnik.contrib.socials',
    'aparnik.contrib.sliders',
    'aparnik.contrib.settings',
    'aparnik.contrib.counters',
    'aparnik.contrib.notifications',
    'aparnik.contrib.messaging',
    'aparnik.contrib.chats',
    'aparnik.contrib.notifiesme',
    'aparnik.contrib.shortblogs',
    'aparnik.contrib.supports',
    'aparnik.contrib.faq',
    'aparnik.contrib.termsandconditions',
    'aparnik.contrib.categories',
    'aparnik.contrib.pages',
    'aparnik.contrib.segments',
    'aparnik.contrib.buttons',
    'aparnik.contrib.tickets',
    'aparnik.packages.shops.products',
    'aparnik.packages.shops.productssharing',
    'aparnik.packages.bankgateways.zarinpals',
    'aparnik.packages.shops.payments',
    'aparnik.packages.shops.subscriptions',
    'aparnik.packages.shops.orders',
    'aparnik.packages.shops.coupons',
    'aparnik.packages.shops.cosales',
    'aparnik.packages.shops.vouchers',
    'aparnik.packages.shops.files',
    'aparnik.packages.educations.educations',
    'aparnik.packages.educations.books',
    'aparnik.packages.educations.teachers',
    'aparnik.packages.educations.courses',
    'aparnik.packages.educations.progresses',
    'aparnik.packages.news',

)

MIDDLEWARE = (
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sites.middleware.CurrentSiteMiddleware',
    # third party
    # 'DJANGO_PROJECT.middleware.WebFactionFixes',
    'DJANGO_PROJECT.middleware.DisableCSRFMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)
# ROOT_URLCONF = 'DJANGO_PROJECT.urls.common_urls'
ROOT_URLCONF = 'DJANGO_PROJECT.urls'
ASGI_APPLICATION = "DJANGO_PROJECT.routing.application"

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

# WSGI_APPLICATION = 'DJANGO_PROJECT.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
    }
}

FILE_UPLOAD_HANDLERS = [
    'django.core.files.uploadhandler.TemporaryFileUploadHandler',
    'django.core.files.uploadhandler.MemoryFileUploadHandler',
]

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


LANGUAGE_CODE = 'fa-ir'  # 'en-us'
# LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Tehran'

USE_I18N = True

USE_L10N = True

USE_TZ = os.environ.get('USE_TZ', "True") == "True"

LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale/'),
)

LANGUAGES = [
    ('fa', _('Persian')),
    # ('en', _('English')),
    # ('es', _('Espaniol')),
]

# Django Rest Framework

REST_FRAMEWORK = {
    # Attention: change it for custom handle
    # 'EXCEPTION_HANDLER': 'users.utils.custom_exception_handler',
    'DEFAULT_PERMISSION_CLASSES': (
        # 'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        # Attention: change it for custom json response
        # 'users.customJSON.CustomJSONRenderer',
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'PAGE_SIZE': 25,
}

# Allow all host headers
ALLOWED_HOSTS = ['*']

# STATICFILES_DIRS = (
#     os.path.join(BASE_DIR, 'static'),
# )


JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
        'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
        'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
        'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
        'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    # 'users.api.views.jwt_response_payload_handler',
        'aparnik.contrib.users.api.views.jwt_response_payload_handler',
    # 'rest_framework_jwt.utils.jwt_response_payload_handler',
    # 'my_jwt.views.jwt_response_payload_handler',

    'JWT_SECRET_KEY': SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=300),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,

    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'APARNIK',
    'JWT_AUTH_COOKIE': None,

}

# Django debug toolbar
DEBUG_TOOLBAR_PATCH_SETTINGS = True
INTERNAL_IPS = ('127.0.0.1',)

CORS_ORIGIN_ALLOW_ALL = True

# CORS_ORIGIN_WHITELIST = (
#     'restzahedipro.s3.amazonaws.com',
# )
# CORS_ORIGIN_ALLOW_ALL = True
# Access-Control-Allow-Origin: *

# jalali date time
JALALI_FORMAT = os.environ.get('JALALI_FORMAT', "%Y/%m/%d")

APARNIK = {
    'AWS_ACTIVE': os.environ.get('AWS_ACTIVE', "False") == "True",
    'BANK_ACTIVE': os.environ.get('BANK_ACTIVE', "False") == "True",
    'ZARINPAL_MERCHENT_CODE': os.environ.get('ZARINPAL_MERCHENT_CODE', ''),
    # 'USER_UPDATE_SERIALIZER': 'users.api.serializers.UserUpdateSerializer',
    'USER_LOGIN_WITH_PASSWORD': os.environ.get('USER_LOGIN_WITH_PASSWORD', "True") == "True",
    # 'USER_LOGIN_API_VIEW': 'users.api.views.UserLoginAPIView',
    # 'USER_IS_SHOW_ADMIN_PANEL': False,
    'USER_REGISTER_WITH_LOGIN': os.environ.get('USER_REGISTER_WITH_LOGIN', "True") == "True",
    'API_PRODUCT_MODE': os.environ.get('DJANGO_API_PRODUCT_MODE', "True") == "True",
    'SMS_EXPIRE_TOKEN': os.environ.get('SMS_EXPIRE_TOKEN', 180),
    'SMS_API_KEY': os.environ.get('SMS_API_KEY', ''),
    'SMS_OTA_NAME': os.environ.get('SMS_OTA_NAME', ""),
    'SEND_SMS': os.environ.get('SEND_SMS', 'True') == 'True',
    'VERIFY_FAKE': os.environ.get('VERIFY_FAKE', 'False') == 'True',
    'VERIFY_FAKE_CODE': os.environ.get('VERIFY_FAKE_CODE', ''),
    'JALALI_FORMAT': JALALI_FORMAT,
}

AWS_ACTIVE = APARNIK['AWS_ACTIVE']
USER_LOGIN_WITH_PASSWORD = APARNIK['USER_LOGIN_WITH_PASSWORD']

CKEDITOR_CONFIGS = {
    'basic': {
        'toolbar': 'Basic',
    },
    'advance': {
        'toolbar': 'Advance',
    },
    'custom': {
        'toolbar': 'Custom',
        'toolbar_Custom': [
            {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
            {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']},
            {'name': 'colors', 'items': ['TextColor', 'BGColor']},
            {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
            {'name': 'forms',
             'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
                       'HiddenField']},
            {'name': 'basicstyles',
             'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
            {'name': 'paragraph',
             'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
                       'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
                       'Language']},
            {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
            {'name': 'insert',
             'items': ['Table', 'HorizontalRule', 'Smiley', 'SpecialChar']},  # 'Image', 'Flash','PageBreak', 'Iframe'
        ]
    }
}

CKEDITOR_UPLOAD_PATH = "/"

TAGGIT_CASE_INSENSITIVE = True

# User
# AUTH_USER_MODEL = 'users.User'
# AUTHENTICATION_BACKENDS = ('aparnik.contrib.users.backends.AuthBackend', 'django.contrib.auth.backends.ModelBackend')
AUTH_USER_MODEL = 'aparnik_users.User'
AUTHENTICATION_BACKENDS = (
    'aparnik.contrib.users.backends.AuthBackend',
    # 'django.contrib.auth.backends.ModelBackend'
)

NOTIFICATION_API_KEY = os.environ.get('NOTIFICATION_API_KEY', None)
NOTIFICATION_APP_ID = os.environ.get('NOTIFICATION_APP_ID', None)
FCM_DJANGO_SETTINGS = {
    'FCM_SERVER_KEY': NOTIFICATION_API_KEY,
    # true if you want to have only one active device per registered user at a time
    # default: False
    'ONE_DEVICE_PER_USER': False,
    # devices to which notifications cannot be sent,
    # are deleted upon receiving error response from FCM
    # default: False
    'DELETE_INACTIVE_DEVICES': False,
}

TINYMCE_DEFAULT_CONFIG = {
    'height': 360,
    'width': 1120,
    'cleanup_on_startup': True,
    'custom_undo_redo_levels': 20,
    'selector': 'textarea',
    'theme': 'modern',
    'plugins': 'textcolor save link image media preview codesample contextmenu table code lists fullscreen  insertdatetime  nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists  charmap print  hr anchor pagebreak',
    'toolbar1': 'save fullscreen bold italic underline,fontselect,fontsizeselect  | forecolor backcolor | alignleft aligncenter alignright alignjustify'
                '| bullist numlist | outdent indent | table | link image media | codesample | preview code |',
    'contextmenu': 'formats | link image',

    'menubar': True,
    'statusbar': True,

}

# Filebrowser
FILEBROWSER_DIRECTORY = ''
DIRECTORY = ''

# notifications settings
NOTIFICATIONS_CHANNELS = {
    'websocket': 'aparnik.contrib.messaging.channels.BasicWebSocketChannel',
    'push': 'aparnik.contrib.messaging.channels.BasicPushNotificationChannel',
}


CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}

SMS_CHANNEL = 'aparnik.utils.sms_api.SMSAPIKavenegar'
