from collections import defaultdict
from datetime import datetime, timedelta, time

from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from corehq.apps.users.util import WEIRD_USER_IDS

from dimagi.utils.couch.database import get_db
from corehq.couchapps.models import ReportsForm
from corehq.apps.domain.models import Domain
from corehq.apps.reminders.models import CaseReminderHandler
from corehq.apps.reports.util import make_form_couch_key
from corehq.apps.users.models import CouchUser
from corehq.elastic import es_query, ADD_TO_ES_FILTER, ES_URLS
from corehq.pillows.mappings.case_mapping import CASE_INDEX
from corehq.pillows.mappings.xform_mapping import XFORM_INDEX


def num_web_users(domain, *args):
    key = ["active", domain, 'WebUser']
    row = get_db().view('users/by_domain', startkey=key, endkey=key+[{}]).one()
    return row["value"] if row else 0

def num_mobile_users(domain, *args):
    row = get_db().view('users/by_domain', startkey=[domain], endkey=[domain, {}]).one()
    return row["value"] if row else 0

DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
DISPLAY_DATE_FORMAT = '%Y/%m/%d %H:%M:%S'

def active_mobile_users(domain, *args):
    """
    Returns the number of mobile users who have submitted a form in the last 30 days
    """
    now = datetime.now()
    then = (now - timedelta(days=30)).strftime(DATE_FORMAT)
    now = now.strftime(DATE_FORMAT)

    q = {"query": {
            "range": {
                "form.meta.timeEnd": {
                    "from": then,
                    "to": now}}},
         "filter": {"and": ADD_TO_ES_FILTER["forms"][:]}}

    facets = ['form.meta.userID']
    data = es_query(params={"domain.exact": domain}, q=q, facets=facets, es_url=XFORM_INDEX + '/xform/_search', size=1)
    terms = [t.get('term') for t in data["facets"]["form.meta.userID"]["terms"]]
    user_ids = CouchUser.ids_by_domain(domain)
    return len(filter(lambda t: t and t in user_ids, terms))