#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: __init__.py 9500 2015-11-17 03:10:51Z Eric $
#
# Copyright (c) 2015 Nuwa Information Co., Ltd, All Rights Reserved.
#
# Licensed under the Proprietary License,
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at our web site.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# $Author: Eric $ (last)
# $Date: 2015-11-17 11:10:51 +0800 (Tue, 17 Nov 2015) $
# $Revision: 9500 $

import os
import sys
import warnings

from Iuno import warnWithout, update, require
from Iuppiter.DjangoUtil import extendInstalledApps, extendMiddlewareClasses, \
                                extendTemplateContextProcessors


def attachSettings(settingsDict, enableFacebook=False, enableGoogle=False,
                   enableLive=False, enableYahoo=False):
    """
    Attach default settings to settings.py.
    It must be called in settings by passing locals().

    @param settingsDict locals() in settings.py.
    @param enableFacebook enable Facebook social login or not
    @param enableGoogle enable Google social login or not
    @param enableLive enable Live social login or not
    @param enableYahoo enable Yahoo social login or not
    """
    #=========================================================================
    # Django plugins.

    ADDING_INSTALLED_APPS = (
        'account',
        'pinax_theme_bootstrap', 
        'bootstrapform',
        'social.apps.django_app.default',
    )
    
    ADDING_MIDDLEWARE_CLASSES = (
        'account.middleware.LocaleMiddleware',
        'account.middleware.TimezoneMiddleware',
    )

    extendInstalledApps(settingsDict, ADDING_INSTALLED_APPS)

    extendMiddlewareClasses(settingsDict, ADDING_MIDDLEWARE_CLASSES)
    #=========================================================================
    
    #=========================================================================
    # Email.
    emailDefaults = {
        'ACCOUNT_EMAIL_CONFIRMATION_REQUIRED' : True,
        'EMAIL_BACKEND' : 'django.core.mail.backends.smtp.EmailBackend',
    }
    
    warnWithout('EMAIL_BACKEND', settingsDict, emailDefaults)

    update(settingsDict, emailDefaults)
    #=========================================================================
    
    #=========================================================================
    # authentication backends.
    authenticationBackends = [            
        'account.auth_backends.EmailAuthenticationBackend',
        'django.contrib.auth.backends.ModelBackend',
    ]
    
    if enableFacebook:
        authenticationBackends.append('social.backends.facebook.FacebookOAuth2')
        
    if enableGoogle:
        authenticationBackends.append('social.backends.google.GoogleOAuth2')
            
    if enableYahoo:
        authenticationBackends.append('social.backends.yahoo.YahooOpenId')
        
    if enableLive:
        authenticationBackends.append('social.backends.live.LiveOAuth2')

    authenticationBackends = tuple(authenticationBackends)
    
    authenticationBackendsDefaults = {
        'AUTHENTICATION_BACKENDS' : 
            authenticationBackends,
        'SESSION_SERIALIZER' : 
            'django.contrib.sessions.serializers.PickleSerializer'
    }

    update(settingsDict, authenticationBackendsDefaults)
    #=========================================================================
    
    #=========================================================================
    #  Django templates.
    ADDING_TEMPLATES_CONTEXT_PROCESSORS = (
        "account.context_processors.account",
        "django.core.context_processors.request", 
        "pinax_theme_bootstrap.context_processors.theme",
        "social.apps.django_app.context_processors.backends",
        "social.apps.django_app.context_processors.login_redirect",                             
    )
    
    extendTemplateContextProcessors(settingsDict, 
                                    ADDING_TEMPLATES_CONTEXT_PROCESSORS)
    #=========================================================================
    
    #=========================================================================
    #  social_auth pipeline.
    socialAuthPipelineDefaults = {
        'SOCIAL_AUTH_PIPELINE' : ( 
            'social.pipeline.social_auth.social_details',
            'social.pipeline.social_auth.social_uid',
            'social.pipeline.social_auth.auth_allowed',
            'social.pipeline.social_auth.social_user',
            'social.pipeline.user.get_username',
            'social.pipeline.user.create_user',
            #'path.to.save_profile',  # <--- set the path to the function
            'social.pipeline.social_auth.associate_user',
            'social.pipeline.social_auth.load_extra_data',
            'social.pipeline.user.user_details',
        ) 
    }

    update(settingsDict, socialAuthPipelineDefaults)
    #=========================================================================
    
    #=========================================================================
    #  socail_auth basic settings.
    socailAuthSettingsDefaults = {
        'SOCIAL_AUTH_UID_LENGTH' : 16,
        'SOCIAL_AUTH_ASSOCIATION_HANDLE_LENGTH' : 16,
        'SOCIAL_AUTH_NONCE_SERVER_URL_LENGTH' : 16,
        'SOCIAL_AUTH_ASSOCIATION_SERVER_URL_LENGTH' : 16,
    }
    
    if enableFacebook:
        socailAuthSettingsDefaults[
            'SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS'] = {
          'locale': 'zh-tw',
          'fields': 'id, name, first_name, last_name, email, age_range'
        }
        socailAuthSettingsDefaults['SOCIAL_AUTH_FACEBOOK_SCOPE'] = ['email']
        require('SOCIAL_AUTH_FACEBOOK_KEY', settingsDict)
        require('SOCIAL_AUTH_FACEBOOK_SECRET', settingsDict)
        
    if enableGoogle:
        require('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', settingsDict)
        require('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', settingsDict)
        
    if enableLive:
        socailAuthSettingsDefaults['SOCIAL_AUTH_LIVE_SCOPE'] = \
            ['wl.basic', 'wl.emails']
        require('SOCIAL_AUTH_LIVE_KEY', settingsDict)
        require('SOCIAL_AUTH_LIVE_SECRET', settingsDict)

    update(settingsDict, socailAuthSettingsDefaults)
    #=========================================================================
    