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

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


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',
    'rest_framework',
    'api',
    'account',
    'group',
    'message',
    'operation',
    'page',
    'pay',
    'photo',
    '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',
)

MIDDLEWARE_CLASSES += ('multidomain.middleware.DomainMiddleware', )

URL_CONFIG = (
    # (r'^(.+\.)?xfoto\.com\.cn', 'pai2.urls_www'),
    (r'^(.+\.)?api\.pai\.ai', 'pai2.urls_api'),
)

ROOT_URLCONF = 'pai2.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 = 'pai2.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pai2',
        'USER': 'root',
        'PASSWORD': '',
        'CONN_MAX_AGE': 600,
        'OPTIONS': {
            # Utf8mb4 for Emoji
            # UserInfo ==> nickname
            #   ALTER TABLE account_userinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
            # GroupUserInfo ==> nickname
            #   ALTER TABLE group_groupuserinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # GroupPhotoInfo ==> nickname
            #   ALTER TABLE group_groupphotoinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # PhotoCommentInfo ==> nickname
            #   ALTER TABLE group_photocommentinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # PhotoThumbUpInfo ==> nickname
            #   ALTER TABLE group_photothumbupinfo MODIFY COLUMN nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            # UserMessageInfo ==> nickname
            #   ALTER TABLE message_usermessageinfo MODIFY COLUMN from_nickname VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL;
            'charset': 'utf8mb4',
        },
    }
}

SCHEMES = {
    'django.db.backends.postgresql_psycopg2': 'postgres',
    'django.db.backends.postgresql_psycopg2': 'postgresql',
    'django.db.backends.postgresql_psycopg2': 'pgsql',
    'django.contrib.gis.db.backends.postgis': 'postgis',
    'django.db.backends.mysql': 'mysql',
    # 'django.db.backends.mysql': 'mysql2',
    'django.contrib.gis.db.backends.mysql': 'mysqlgis',
    'mysql.connector.django': 'mysql-connector',
    'django.contrib.gis.db.backends.spatialite': 'spatialite',
    'django.db.backends.sqlite3': 'sqlite',
    'django.db.backends.oracle': 'oracle',
    'django.contrib.gis.db.backends.oracle': 'oraclegis',
}

DATABASE_URL = {
    k: '{scheme}://{user}:{password}@{host}:{port}/{name}?charset={charset}'.format(
        scheme=SCHEMES[v.get('ENGINE', '')],
        user=v.get('USER', 'root'),
        password=v.get('PASSWORD', ''),
        host=v.get('HOST', 'localhost'),
        port=v.get('PORT', 6039),
        name=v.get('NAME', ''),
        charset=v.get('OPTIONS', {}).get('charset', 'utf8'),
    ) for k, v in DATABASES.iteritems()
}

# 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/'

# logger setting
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': {
            'level': 'DEBUG',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': '/tmp/logit.log',
            'when': 'midnight',
            'backupCount': 10,
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'logit': {
            'handlers': ['logit'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

# 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,
    }
}

# Redis 缓存时间设置
REDIS_EXPIRED_HOUR = 3600  # 60 * 60
REDIS_EXPIRED_DAY = 86400  # 24 * 60 * 60
REDIS_EXPIRED_WEEK = 604800  # 7 * 24 * 60 * 60
REDIS_EXPIRED_MONTH = 2678400  # 31 * 24 * 60 * 60
REDIS_EXPIRED_YEAR = 31622400  # 366 * 24 * 60 * 60

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

WECHAT_GET_CODE_BASE = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect'
WECHAT_GET_CODE_USERINFO = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect'
WECHAT_GET_OAUTH2_ACCESS_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code'

WECHAT_GET_USERINFO = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s'

# 微信支付设置
WXPAY_NOTIFY_SUCCESS = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'
WXPAY_NOTIFY_FAIL = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[XML PARSE FAIL]]></return_msg></xml>'

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

# 唯一标识设置
CURTAIL_UUID_LENGTH = 7

# 水印设置
WATERMARK_LOGO = os.path.join(PROJ_DIR, 'static/pai2/img/paiai_96_96.png').replace('\\', '/')

# 缩略图设置
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

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

# 下载设置
DOWNLOAD_WX_URL = ''
DOWNLOAD_IOS_URL = ''

# 群组设置
GROUP_PER_PAGE = 20  # 群组每页数量

# 游客设置
GUEST_USER_ID = 'guest'

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

# 价格设置
LENSMAN_PHOTO_HAGGLE_MAX_TIMES = 3  # 摄影师照片最大砍价次数

# 订单设置
ORDER_NUM_PER_PAGE = 10  # 订单每页数量

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

# 消息图片设置
PAI2_LOGO_URL = DOMAIN + '/static/pai2/img/paiai_96_96.png'

SYSTEM_MESSAGE_AVATAR = PAI2_LOGO_URL
COMMENT_MESSAGE_AVATAR = PAI2_LOGO_URL
THUMBUP_MESSAGE_AVATAR = PAI2_LOGO_URL

MESSAGE_NUM_PER_PAGE = 10  # 消息每页数量

try:
    from local_settings import *
except ImportError:
    pass

try:
    from func_settings import redis_connect
    REDIS_CACHE = redis_connect(REDIS.get('default', {}))
except ImportError:
    REDIS_CACHE = None
