"""
Django settings for AutomatedTestPlatform project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import logging
from pathlib import Path
import os

ENV_PROFILE = os.getenv("ENV")
# ENV_PROFILE = "macOS"
ENV_cmd = os.getenv("CmdRunner")

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

if ENV_PROFILE == "SERVER":
    # 生产环境地址
    ALLOWED_HOSTS = ["172.16.0.82", "127.0.0.1"]
    # ALLOWED_HOSTS = ['*']

    # 配置自动化脚本日志文件的存储位置
    WEB_ROOT = os.path.join('/home/quant_group/data/Web_Script')

    # 配置上传文件的存储位置
    JMETER_ROOT = os.path.join('/home/quant_group/data/jmeter/jmeter_script')

    # 配置上传jmeter参数化文件的存储位置
    JMETER_DATA_SET_ROOT = os.path.join('/home/quant_group/data/jmeter/jmeter_data_set')

    # jmeter测试报告
    JMETER_REPORT = os.path.join('/home/quant_group/data/jmeter/jmeter_report/Report')
    JMETER_REPORT_URL = "/home/quant_group/data/jmeter/jmeter_report/Report"

    # API测试用例上传 excel
    API_TEST_CASE_ROOT = os.path.join('/data/api_test_case_excel/')

    # 访问资源上传的路径
    WEB_URL = "/home/quant_group/data/Web_Script/"
    CORS_ALLOWED_ORIGINS = (
        ['http://127.0.0.1:*', 'http://172.16.0.82:*']

    )

    # mysql

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS': {
                'read_default_file': BASE_DIR + '/release.cnf',
                'init_command': 'SET foreign_key_checks = 0;',
                'charset': 'utf8mb4',
            },
        }
    }
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
            'standard': {
                'format': ' [%(levelname)s] %(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] '
                          '[%(module)s:%(funcName)s] - %(message)s'}
        },
        'filters': {
        },
        'handlers': {
            'default': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': '/home/quant_group/data/log/release_log/all.log',  # 日志输出文件
                'maxBytes': 1024 * 1024 * 30,  # 文件大小
                'backupCount': 2,  # 备份份数
                'formatter': 'standard',  # 使用哪种formatters日志格式
                'encoding': 'utf-8',
            },
            'error': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': '/home/quant_group/data/log/release_log/error.log',
                'maxBytes': 1024 * 1024 * 30,
                'backupCount': 2,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'info': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': '/home/quant_group/data/log/release_log/info.log',
                'maxBytes': 1024 * 1024 * 30,
                'backupCount': 2,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
        },
        'loggers': {
            'django': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False
            },
            'django.request': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False,
            },
            'interface': {
                'handlers': ['default', 'info', 'console', 'error'],
                'level': 'INFO',
                'propagate': False,
            },
        }
    }

elif ENV_PROFILE == "1":
    print("windows环境")
    # 测试环境地址
    ALLOWED_HOSTS = ["127.0.0.1", "localhost", "172.16.0.82"]
    # 配置自动化脚本日志文件的存储位置
    # WEB_ROOT = os.path.join(BASE_DIR, 'web_log/test_log')
    WEB_ROOT = os.path.join('D:\\web_log\\test_log')

    # 配置上传文件的存储位置
    JMETER_ROOT = os.path.join('D:\\jmeter_script')

    # 配置上传jmeter参数化文件的存储位置
    JMETER_DATA_SET_ROOT = os.path.join('D:\\jmeter_script_data_set')

    # jmeter测试报告
    JMETER_REPORT = os.path.join('D:/jmeter_report/Report')

    # 配置上传api测试用例文件的存储位置
    API_TEST_CASE_ROOT = os.path.join('D:\\api_test_case_excel\\')

    # 访问资源上传的路径
    WEB_URL = "/Web_Script/"

    CORS_ORIGIN_WHITELIST = (
        ['http://127.0.0.1:*', 'https://10.0.17.184:*', 'http://172.16.0.82:*']

    )

    # mysql
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS': {
                'read_default_file': BASE_DIR + '/dev.cnf',
                'init_command': 'SET foreign_key_checks = 0;',
                'charset': 'utf8mb4',
            },
        }
    }

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
            'standard': {
                'format': ' [%(levelname)s] %(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] '
                          '[%(module)s:%(funcName)s] - %(message)s'}
        },
        'filters': {
        },
        'handlers': {
            'default': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': 'D:/log/test_log/all.log',  # 日志输出文件
                'maxBytes': 1024 * 1024 * 30,  # 文件大小
                'backupCount': 5,  # 备份份数
                'formatter': 'standard',  # 使用哪种formatters日志格式
                'encoding': 'utf-8',
            },
            'error': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': 'D:/log/test_log/error.log',
                'maxBytes': 1024 * 1024 * 30,
                'backupCount': 5,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'info': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': 'D:log/test_log/info.log',
                'maxBytes': 1024 * 1024 * 5,
                'backupCount': 5,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
        },
        'loggers': {
            'django': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False
            },
            'django.request': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False,
            },
            'interface': {
                'handlers': ['default', 'info', 'console', 'error'],
                'level': 'INFO',
                'propagate': False,
            },
        }
    }

elif ENV_PROFILE == "macOS":
    print("本地MAC测试")
    # 测试环境地址
    ALLOWED_HOSTS = ["127.0.0.1", "localhost"]
    # 配置自动化脚本日志文件的存储位置
    WEB_ROOT = os.path.join('/Users/mac/Web_Script')

    # 配置上传文件的存储位置
    JMETER_ROOT = os.path.join('/Users/mac/jmeter_script')

    # 配置上传jmeter参数化文件的存储位置
    JMETER_DATA_SET_ROOT = os.path.join('/Users/mac/jmeter_data')

    # jmeter测试报告
    JMETER_REPORT = os.path.join('/Users/mac/jmeter_report/Report')
    JMETER_REPORT_URL = "/Users/mac/jmeter_report/Report"

    # 配置上传api测试用例文件的存储位置
    API_TEST_CASE_ROOT = os.path.join(BASE_DIR)

    # 访问资源上传的路径
    WEB_URL = "/Web_Script/"

    # CORS_ORIGIN_WHITELIST = (
    #     ['http://127.0.0.1:*', 'https://10.0.17.184:*']
    #
    # )
    # mysql
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS': {
                'read_default_file': BASE_DIR + '/dev.cnf',
                'init_command': 'SET foreign_key_checks = 0;',
                'charset': 'utf8mb4',
            },
        }
    }

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
            'standard': {
                'format': ' [%(levelname)s] %(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] '
                          '[%(module)s:%(funcName)s] - %(message)s'}
        },
        'filters': {
        },
        'handlers': {
            'default': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': '/Users/mac/testPlatformLog/all.log',  # 日志输出文件
                'maxBytes': 1024 * 1024 * 30,  # 文件大小
                'backupCount': 5,  # 备份份数
                'formatter': 'standard',  # 使用哪种formatters日志格式
                'encoding': 'utf-8',
            },
            'error': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': '/Users/mac/testPlatformLog/error.log',
                'maxBytes': 1024 * 1024 * 30,
                'backupCount': 5,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'simple'
            },
            'info': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': '/Users/mac/testPlatformLog/info.log',
                'maxBytes': 1024 * 1024 * 5,
                'backupCount': 5,
                'formatter': 'standard',
                'encoding': 'utf-8',
            },
        },
        'loggers': {
            'django': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False
            },
            'django.request': {
                'handlers': ['default', 'console'],
                'level': 'INFO',
                'propagate': False,
            },
            'interface': {
                'handlers': ['default', 'info', 'console', 'error'],
                'level': 'INFO',
                'propagate': False,
            },
        }
    }

# Build paths inside the project like this: BASE_DIR / 'subdir'.
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 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 = '$5k4rpds2$k1y1wtw25-+qc4n^b4en=lvo)6o^=pt3-2exqp_6'

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

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'automated_main',
    'channels',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 'whitenoise.middleware.WhiteNoiseMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 添加上这个中间件
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'automated_main.middleware.my_middle_ware.MyMiddleWare',
]

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    ['http://127.0.0.1:*', 'http://172.16.0.82:*']

)
CORS_URLS_REGEX = r'^/api/.*$'

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'accept'
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

ROOT_URLCONF = 'AutomatedTestPlatform.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',
            ],
        },
    },
]

REST_FRAMEWORK = {
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}

WSGI_APPLICATION = 'AutomatedTestPlatform.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
# sqlite3
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'dev.sqlite3'),
    }
}
"""

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

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/2.0/topics/i18n/

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

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

STATIC_URL = '/static/'

# # 配置上传文件的存储位置
# JMETER_ROOT = os.path.join(BASE_DIR, 'jmeter_script')

# web脚本模板位置
WEB_TEMPLATE = os.path.join(BASE_DIR, 'automated_main/view/ui_automation/ui_test_task/extend/TestScriptTemplate.py')

# API测试用例模板位置
API_TEMPLATE = os.path.join(BASE_DIR,
                            'automated_main/view/api_automation/api_test_case/extend/ApiTestCaseTemplate.xlsx')

# 访问资源上传的路径
JMETER_URL = "/jmeter_script/"

API_TEST_CASE_URL = "/api_test_cases_excel/"

# 访问性能报告上传的路径
JMETER_REPORT_URL = "/data/jmeter_report/Report/"

# 访问性能脚本参数化上传的路径
JMETER_DATA_SET_URL = "/jmeter_data_set/"

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

SESSION_ENGINE = 'django.contrib.sessions.backends.db'  # 引擎（默认）
SESSION_COOKIE_NAME = "sessionid"  # Session的cookie保存在浏览器上时的key，即：sessionid＝随机字符串（默认）
SESSION_COOKIE_PATH = "/"  # Session的cookie保存的路径（默认）
SESSION_COOKIE_DOMAIN = None  # Session的cookie保存的域名（默认）
SESSION_COOKIE_SECURE = False  # 是否Https传输cookie（默认）
SESSION_COOKIE_HTTPONLY = True  # 是否Session的cookie只支持http传输（默认）
SESSION_COOKIE_AGE = 1209600  # Session的cookie失效日期（2周）（默认）
SESSION_EXPIRE_AT_BROWSER_CLOSE = False  # 是否关闭浏览器使得Session过期（默认）
SESSION_SAVE_EVERY_REQUEST = False  # 是否每次请求都保存Session，默认修改之后才保存（默认
SESSION_COOKIE_SAMESITE = None

# 指定ASGI的路由地址
ASGI_APPLICATION = 'AutomatedTestPlatform.asgi.application'
