import os
import logging

from django import http, setup
from django.core.management import execute_from_command_line


log = logging.getLogger(__name__)


class QueryDict(http.QueryDict):
    def __init__(self, qs=None, mutable=True, encoding='utf-8'):
        http.QueryDict.__init__(self, qs, mutable, encoding)

    def pop(self, key, default=None):
        try:
            val = http.QueryDict.pop(self, key)
        except KeyError:
            return default

        if val == []:
            return default

        return val[0]

    def poplist(self, *args, **kwargs):
        return http.QueryDict.pop(self, *args, **kwargs)


def setup_environ(django_settings_module='intranet.search.settings.django.settings',
                  celery_config_module='intranet.search.settings.celery.config',
                  celery_local_config_module='intranet.search.settings.celery.local_config'):
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
    os.environ.setdefault('CELERY_CONFIG_MODULE', celery_config_module)
    os.environ.setdefault('CELERY_LOCAL_CONFIG_MODULE', celery_local_config_module)
    setup()


def manage():
    setup_environ()

    execute_from_command_line()
