# -*- coding: utf-8 -*-

"""
Django settings for kodo 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

from django_redis_connector import connector


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJ_DIR = os.path.abspath(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 = 'aam6@6bh17d87bn-ax1@mcdrtbfm02y)_twd&!ewrr2^4581!c'

# 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_file_upload',
    'django_uniapi',
    'django_admin',
    'django_rlog',
    'django_we',
    'api',
    'account',
    'box',
    'group',
    'integral',
    'mch',
    'message',
    'miniapp',
    'operation',
    'page',
    'pay',
    'photo',
    'pre',
    'product',
    'server',
    'statistic',
    'website',
)

INSTALLED_APPS += ('multidomain', )

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'detect.middleware.UserAgentDetectionMiddleware',
    'mobi.middleware.MobileDetectionMiddleware',
)

# MIDDLEWARE_CLASSES += ('multidomain.middleware.DomainMiddleware', )
#
# URL_CONFIG = (
#     # (r'^(.+\.)?xfoto\.com\.cn', 'kodo.urls_www'),
#     (r'^(.+\.)?api\.pai\.ai', 'kodo.urls_api'),
# )

ROOT_URLCONF = 'kodo.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',
            ],
            'loaders': [
                ('django.template.loaders.cached.Loader', [
                    'django.template.loaders.filesystem.Loader',
                    'django.template.loaders.app_directories.Loader',
                ]),
            ],
        },
    },
]

WSGI_APPLICATION = 'kodo.wsgi.application'


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

DATABASES = {
    # Create Database
    # CREATE DATABASE kodo DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'kodo',
        'USER': 'root',
        'PASSWORD': '',
        'CONN_MAX_AGE': 600,
        'OPTIONS': {
            # Utf8mb4 for Emoji
            #
            # Nickname
            #
            # account.WechatInfo ==> nickname
            #   ALTER TABLE account_wechatinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
            # account.UserInfo ==> nickname
            #   ALTER TABLE account_userinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
            # group.GroupUserInfo ==> nickname
            #   ALTER TABLE group_groupuserinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # group.GroupPhotoInfo ==> nickname
            #   ALTER TABLE group_groupphotoinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # group.PhotoCommentInfo ==> nickname
            #   ALTER TABLE group_photocommentinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # group.PhotoThumbUpInfo ==> nickname
            #   ALTER TABLE group_photothumbupinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # group.UserMessageInfo ==> nickname
            #   ALTER TABLE message_usermessageinfo MODIFY COLUMN from_nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            #
            # Comment
            # group.PhotoCommentInfo ==> comment
            #   ALTER TABLE group_photocommentinfo MODIFY COLUMN comment LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
            'charset': 'utf8mb4',
        },
    }
}

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

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATICFILES_DIRS = (
    os.path.join(PROJ_DIR, 'static').replace('\\', '/'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'collect_static').replace('\\', '/')

STATIC_URL = '/static/'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')

MEDIA_URL = '/media/'

# REST_FRAMEWORK 设置
# See http://www.django-rest-framework.org/#example
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    # 'DEFAULT_PERMISSION_CLASSES': [
    #     'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    # ]
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',),
    'PAGE_SIZE': 1
}

# Redis 设置
REDIS = {
    'default': {
        'HOST': '127.0.0.1',
        'PORT': 6379,
        'USER': '',
        'PASSWORD': '',
        'db': 0,
    }
}

# 微信设置
WECHAT = {
    'JSAPI': {
        'token': '5201314',
        'appID': '',
        'appsecret': '',
        'mchID': '',
        'apiKey': '',
        'mch_cert': '',
        'mch_key': '',
        'redpack': {

        }
    },
}

MEMBER_CARD_ID = ''

# 七牛设置
QINIU = {
    'access_key': 'yCE3xWXduLTERkx_vSNVAIHNcg1pje6EwygiRPjP',
    'secret_key': '05sCekniLCgM6-d_PxrH8sFjvEOsx3ev-FgS7R-k',
    'bucket_default': 'photo',
    'buckets': {
        'original': 'http://orf3sfb8s.bkt.clouddn.com',
        'photo': 'http://orf3lnlmb.bkt.clouddn.com',
        'prettify': 'http://orzfu8zxw.bkt.clouddn.com',
        'thumbnail': 'http://orf3ahvt6.bkt.clouddn.com',
        'thumbnail2': 'http://orf3muf5n.bkt.clouddn.com',
        'watermark': 'http://orf3qne9f.bkt.clouddn.com',
    }
}

# 图片设置
FILE_UPLOAD_MAX_MEMORY_SIZE = 5242880  # InMemoryUploadedFile 文件最大值
FILE_UPLOAD_PERMISSIONS = 0o644  # TemporaryUploadedFile 文件权限设置

# 唯一标识设置
CURTAIL_UUID_LENGTH = 7  # Used in django-curtail-uuid==1.0.0

# 水印设置
WATERMARK_OR_NOT = False  # 水印是否开启
WATERMARK_LOGO_PATH = os.path.join(PROJ_DIR, 'static/kodo/img/paiai_water_mark.png').replace('\\', '/')  # 水印图片路径

# 原图设置
LENSMAN_PHOTO_ORIGIN_EXPIRED_MSEL = 604800000  # 摄影师原图过期毫秒数，7d = 7 * 24 * 3600 * 1000msel

# 缩略图设置
THUMBNAIL_MAX_WIDTH = 540
THUMBNAIL_MAX_WIDTH2 = 1080

# 首页设置
PAI2_HOME_PER_PAGE = 20  # 首页照片每页数量
PAI2_HOME_MAX_PAGE = 20  # 首页照片最大页数
PAI2_HOME_MAX_ROWS = 400  # 首页照片最大数量，PAI2_HOME_PER_PAGE * PAI2_HOME_MAX_PAGE = 20 * 20 = 400

# 下载页设置
TMPL_DOWNLOAD_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/download.tmpl.html').replace('\\', '/')

PAI2_USER_DOWNLOAD_ADR_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/kodo_user_adr_download.html').replace('\\', '/')
PAI2_USER_DOWNLOAD_IOS_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/kodo_user_ios_download.html').replace('\\', '/')

PAI2_LENSMAN_DOWNLOAD_ADR_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/kodo_lensman_adr_download.html').replace('\\', '/')
PAI2_LENSMAN_DOWNLOAD_IOS_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/kodo_lensman_ios_download.html').replace('\\', '/')

PAI2_TOURGUIDE_DOWNLOAD_ADR_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/kodo_tourguide_adr_download.html').replace('\\', '/')
PAI2_TOURGUIDE_DOWNLOAD_IOS_PAGE_PATH = os.path.join(BASE_DIR, 'page/templates/page/kodo_tourguide_ios_download.html').replace('\\', '/')

# 下载设置
PAI2_USER_DOWNLOAD_WX_URL = 'https://a.app.qq.com/o/simple.jsp?pkgname=ai.pai.client'
PAI2_USER_DOWNLOAD_IOS_URL = 'https://itunes.apple.com/cn/app/pai-aipaiai/id1163960351?mt=8'

PAI2_LENSMAN_DOWNLOAD_WX_URL = 'https://pai.ai'
PAI2_LENSMAN_DOWNLOAD_IOS_URL = 'https://pai.ai'

PAI2_TOURGUIDE_DOWNLOAD_WX_URL = 'https://pai.ai'
PAI2_TOURGUIDE_DOWNLOAD_IOS_URL = 'https://pai.ai'

# 游客设置
PAI2_TOURGUIDE_GUEST_UNIONID = 'oCGajv3Slxef2RuM4Sr-S2jTZwD4'

# 版本设置
MIN_VERSION = '0.0.0'
MAX_VERSION = '999.999.999'
CURRENT_VERSION = '1.0.0'

# 页码设置
GROUP_NUM_PER_PAGE = 20  # 群组每页数量
MESSAGE_NUM_PER_PAGE = 10  # 消息每页数量
ORDER_NUM_PER_PAGE = 10  # 订单每页数量

# 域名设置
DOMAIN = 'https://pai.ai'
IMG_DOMAIN = 'https://img.pai.ai'
API_DOMAIN = 'https://api.pai.ai'

DOMAIN_HTTP = 'http://pai.ai'
IMG_DOMAIN_HTTP = 'http://img.pai.ai'
API_DOMAIN_HTTP = 'http://api.pai.ai'

# LOGIT 设置
LOGIT_BODY_FLAG = True
LOGIT_RES_FLAG = True

# Django-Admin Settings
# DISABLE_ACTION = False

# KODO 设置
MAKE_PASSWORD_SALT = ''
MAKE_PASSWORD_HASHER = ''

# 错误信息邮件设置
# Email address that error messages come from.
SERVER_EMAIL = 'kimi@pai.ai'
# The email backend to use. For possible shortcuts see django.core.mail.
# The default is to use the SMTP backend.
# Third-party backends can be specified by providing a Python path
# to a module that defines an EmailBackend class.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Host for sending email.
EMAIL_HOST = 'smtp.exmail.qq.com'
# Port for sending email.
EMAIL_PORT = 25
# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = 'kimi@pai.ai'
EMAIL_HOST_PASSWORD = '<^_^>pwd<^_^>'
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
EMAIL_SSL_CERTFILE = None
EMAIL_SSL_KEYFILE = None
EMAIL_TIMEOUT = None
# Default email address to use for various automated correspondence from
# the site managers.
DEFAULT_FROM_EMAIL = 'Kimi <kimi@pai.ai>'
# People who get code error notifications.
# In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')]
ADMINS = [('Kimi', 'kimi@pai.ai')]
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS
# Subject-line prefix for email messages send with django.core.mail.mail_admins
# or ...mail_managers.  Make sure to include the trailing space.
EMAIL_SUBJECT_PREFIX = u'[Kodo] '

# Django-Admin Settings
DISABLE_ACTION = False

# Django-Logit Settings
DJANGO_LOGIT_ENABLED = True

# Test Settings
DEBUG_DATA_FLAG = False

try:
    from local_settings import *
except ImportError:
    pass

try:
    from oauth_settings import *
except ImportError:
    pass

# 官网设置
# location =/  {
#     rewrite ^  $scheme://$host/pc/;
# }
WEBSITE_PC = '{0}/pc/'.format(DOMAIN)
WEBSITE_MOBI = '{0}/pc/'.format(DOMAIN)

# 依赖 local_settings 中的配置
# 微信授权设置
WECHAT_OAUTH2_REDIRECT_URI = '{0}/we/we_oauth2?scope={{0}}redirect_url={{1}}'.format(DOMAIN_HTTP)
WECHAT_BASE_REDIRECT_URI = '{0}/we/base_redirect'.format(DOMAIN_HTTP)
WECHAT_USERINFO_REDIRECT_URI = '{0}/we/userinfo_redirect'.format(DOMAIN_HTTP)

# 消息图片设置
PAI2_LOGO_URL = DOMAIN + '/static/kodo/img/paiai_96_96.png'
SYSTEM_MESSAGE_AVATAR = PAI2_LOGO_URL
COMMENT_MESSAGE_AVATAR = PAI2_LOGO_URL
THUMBUP_MESSAGE_AVATAR = PAI2_LOGO_URL

# Redis 连接
REDIS_CACHE = connector(REDIS.get('default', {}))

# Q_CLUSTER = {
#     'name': 'kodo',
#     'workers': 8,
#     'recycle': 500,
#     'timeout': 60,
#     'compress': True,
#     'cpu_affinity': 1,
#     'save_limit': 250,
#     'queue_limit': 500,
#     'label': 'Django Q',
#     'redis_conn': REDIS_CACHE,
# }

DJLOGIT = {
    'level': 'DEBUG',
    'class': 'rlog.RedisListHandler',
    'redis_client': REDIS_CACHE,
    'key': 'django:logit:kodo',
    'formatter': 'verbose',
}

# 日志设置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'logit': DJLOGIT,
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'logit': {
            'handlers': ['logit'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'console': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}
