import furl
import logging

from django.utils import timezone
from modularodm import Q
from modularodm.exceptions import NoResultsFound, QueryException, ImproperConfigurationError

from website import mails
from website.models import PreprintProvider
from website.settings import DOMAIN, CAMPAIGN_REFRESH_THRESHOLD
from website.util.time import throttle_period_expired


CAMPAIGNS = None
CAMPAIGNS_LAST_REFRESHED = timezone.now()


def get_campaigns():

    global CAMPAIGNS
    global CAMPAIGNS_LAST_REFRESHED

    logger = logging.getLogger(__name__)

    if not CAMPAIGNS or throttle_period_expired(CAMPAIGNS_LAST_REFRESHED, CAMPAIGN_REFRESH_THRESHOLD):

        # Native campaigns: PREREG and ERPC
        CAMPAIGNS = {
            'prereg': {
                'system_tag': 'prereg_challenge_campaign',
                'redirect_url': furl.furl(DOMAIN).add(path='prereg/').url,
                'confirmation_email_template': mails.CONFIRM_EMAIL_PREREG,
                'login_type': 'native',
            },
            'erpc': {
                'system_tag': 'erp_challenge_campaign',
                'redirect_url': furl.furl(DOMAIN).add(path='erpc/').url,
                'confirmation_email_template': mails.CONFIRM_EMAIL_ERPC,
                'login_type': 'native',
            },
        }

        # Institution Login
        CAMPAIGNS.update({
            'institution': {
                'system_tag': 'institution_campaign',
                'redirect_url': '',
                'login_type': 'institution',
            },
        })

        # Proxy campaigns: Preprints, both OSF and branded ones
        try:
            preprint_providers = PreprintProvider.find(Q('_id', 'ne', None))
            for provider in preprint_providers:
                if provider._id == 'osf':
                    template = 'osf'
                    name = 'OSF'
                    url_path = 'preprints/'
                else:
                    template = 'branded'
                    name = provider.name
                    url_path = 'preprints/{}'.format(provider._id)
                campaign = '{}-preprints'.format(provider._id)
                system_tag = '{}_preprints'.format(provider._id)
                CAMPAIGNS.update({
                    campaign: {
                        'system_tag': system_tag,
                        'redirect_url': furl.furl(DOMAIN).add(path=url_path).url,
                        'confirmation_email_template': mails.CONFIRM_EMAIL_PREPRINTS(template, name),
                        'login_type': 'proxy',
                        'provider': name,
                    }
                })
        except (NoResultsFound or QueryException or ImproperConfigurationError) as e:
            logger.warn('An error has occurred during campaign initialization: {}', e)

        CAMPAIGNS_LAST_REFRESHED = timezone.now()

    return CAMPAIGNS


def system_tag_for_campaign(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('system_tag')
    return None


def email_template_for_campaign(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('confirmation_email_template')
    return None


def campaign_for_user(user):
    campaigns = get_campaigns()
    for campaign, config in campaigns.items():
        if config.get('system_tag') in user.system_tags:
            return campaign
    return None


def is_institution_login(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('login_type') == 'institution'
    return None


def is_native_login(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('login_type') == 'native'
    return None


def is_proxy_login(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('login_type') == 'proxy'
    return None


def get_service_provider(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('provider')
    return None


def campaign_url_for(campaign):
    campaigns = get_campaigns()
    if campaign in campaigns:
        return campaigns.get(campaign).get('redirect_url')
    return None

@@ -8,23 +8,8 @@
 furl
-%0Aimport logging
 %0A%0Afr
@@ -43,126 +43,8 @@
 zone
-%0Afrom modularodm import Q%0Afrom modularodm.exceptions import NoResultsFound, QueryException, ImproperConfigurationError
 %0A%0Afr
@@ -376,50 +376,8 @@
 ED%0A%0A
-    logger = logging.getLogger(__name__)%0A%0A
     
@@ -1434,25 +1434,8 @@
 nes%0A
-        try:%0A    
     
@@ -1480,39 +1480,22 @@
 der.
-find(Q('_id', 'ne', None))%0A    
+objects.all()%0A
     
@@ -1546,20 +1546,16 @@
         
-   
- 
 if provi
@@ -1572,20 +1572,16 @@
  'osf':%0A
-    
         
@@ -1617,28 +1617,24 @@
             
-    
 name = 'OSF'
@@ -1642,36 +1642,32 @@
                 
- 
-   
 url_path = 'prep
@@ -1686,20 +1686,16 @@
         
-    
 else:%0A  
@@ -1700,36 +1700,32 @@
                 
-  
-  
 template = 'bran
@@ -1729,20 +1729,16 @@
 randed'%0A
-    
         
@@ -1766,20 +1766,16 @@
 er.name%0A
-    
         
@@ -1833,36 +1833,32 @@
 id)%0A            
-    
 campaign = '%7B%7D-p
@@ -1880,36 +1880,32 @@
 t(provider._id)%0A
-    
             syst
@@ -1957,28 +1957,24 @@
             
- 
-   
 CAMPAIGNS.up
@@ -1988,36 +1988,32 @@
                 
-    
 campaign: %7B%0A    
@@ -2020,36 +2020,32 @@
                 
-   
- 
 'system_tag': sy
@@ -2054,20 +2054,16 @@
 em_tag,%0A
-    
         
@@ -2128,28 +2128,24 @@
 _path).url,%0A
-    
             
@@ -2242,36 +2242,32 @@
                 
-    
 'login_type': 'p
@@ -2293,20 +2293,16 @@
         
-    
 'provide
@@ -2327,20 +2327,16 @@
         
-  
-  
 %7D%0A      
@@ -2345,186 +2345,9 @@
     
-    %7D)%0A        except (NoResultsFound or QueryException or ImproperConfigurationError) as e:%0A            logger.warn('An error has occurred during campaign initialization: %7B%7D', e
+%7D
 )%0A%0A 

Use native django query.