from __future__ import absolute_import, unicode_literals

from celery import shared_task
from celery.utils.log import get_task_logger
from django.conf import settings
from django.core.cache import caches
from elasticsearch import Elasticsearch

from core.utils import dtnow
from events.constants import ELK_HOST, ELK_PORT, ELK_LOGIN, ELK_PASS
from users.models import UserInfo

_log = get_task_logger(__name__)

MEDIA_ROOT = getattr(settings, 'MEDIA_ROOT')
CACHE_TIMEOUT = getattr(settings, 'REDIS_CACHE_TIMEOUT', 120)
REDIS_ELK_EVENTS_KEY = 'amount_of_aggregated_events'


@shared_task
def update_amount_of_aggregated_events():
    """ Task for updating the total amount of aggregated events, stored in elasticsearch """
    es = Elasticsearch([{'host': ELK_HOST, 'port': ELK_PORT}], http_auth=(ELK_LOGIN, ELK_PASS))
    es_search = es.count(index=['aggregated-*', 'system-*'])
    caches['redis'].set(REDIS_ELK_EVENTS_KEY, es_search['count'], CACHE_TIMEOUT)


def expire_users():
    for user_info in UserInfo.objects.filter(expire_date__lte=dtnow().date(), user__is_active=True):
        user_info.user.is_active = False
        user_info.user.save()


@shared_task
def expire_users_task():
    expire_users()
