from django.http import HttpResponse, Http404, FileResponse
from django.conf import settings


def get_and_set_lang(request):
    from django.utils.translation import activate, get_language
    lang = None

    cur_url_list = request.path.split('/')
    if len(cur_url_list) > 1 and cur_url_list[1] in settings.MODELTRANSLATION_LANGUAGES:
        lang = cur_url_list[1]

    if not lang:
        referer_url = request.META.get('HTTP_REFERER')
        if referer_url:
            url_list = referer_url.split('//')
            if len(url_list) > 1:
                url_list = url_list[1].split('/')
                if len(url_list) > 1 and url_list[1] in settings.MODELTRANSLATION_LANGUAGES:
                    lang = url_list[1]

    if not lang:
        lang = get_language()

    if not lang:
        lang = 'en'

    activate(lang)

    return lang


def get_add_to_ajax_response_Dict(user):
    context_Dict = {}

    from ChatServiceApp.funcs import get_unanswered_msgs_count_for_user
    context_Dict.update({
        'unanswered_msgs_count': get_unanswered_msgs_count_for_user(user)
    })

    return context_Dict



def get_inter_Dict(user):

    from SubscribesApp.funcs import get_cur_user_subscribe
    user_subscribe = get_cur_user_subscribe(user)


    Dict = {
        'user_subscribe': user_subscribe,
        'prod': True
    }

    if settings.WS_ADDRESS == 'localhost:8000':
        Dict.update({'prod': False})


    from PushMessages.views import get_key_Dict
    Dict.update(get_key_Dict())

    return Dict

def get_inter_http_response(template_obj, context_Dict, request):

    context_Dict.update(get_inter_Dict(request.user))

    from PushMessages.views import send_push
    if request and 'page' in context_Dict:
        text = None
        title = None

        if context_Dict['page'] == dict:
            if 'title' in context_Dict['page']:
                title = context_Dict['page']['title']
            if 'description' in context_Dict['page']:
                text = context_Dict['page']['description']
        else:
            title = getattr(context_Dict['page'], 'title', None)
            text = getattr(context_Dict['page'], 'description', None)

        # if text and title and not request.user.is_anonymous:
        #     send_push(user=request.user, title=title, text=text)

    from ChatServiceApp.funcs import get_unanswered_msgs_count_for_user
    context_Dict.update({
        'unanswered_msgs_count': get_unanswered_msgs_count_for_user(request.user)
    })

    return HttpResponse(template_obj.render(context_Dict, request))