import logging
import json
import itertools 
import threading
import re
from django.db.models import Count, Sum
from django.contrib.auth.models import User
from math import trunc
from metashare.stats.models import LRStats, QueryStats, UsageStats
from metashare.stats.geoip import getcountry_code, getcountry_name
from metashare.storage.models import PUBLISHED
from metashare.settings import LOG_HANDLER

USAGETHREADNAME = "usagethread"
BOT_AGENT_RE = re.compile(r".*(bot|spider|spyder|crawler|archiver|seek|\
    scooter|wget|misesajour|slurp|agent|gazz|onetszukaj|perl|web|lab|\
    scrubby|asterias|ip3000|knowledge|rambler|search|link|zmeu|hat|appie|\
    yandex|iron33|nazilla|kototoi).*", re.IGNORECASE)

#type of monitored actions
UPDATE_STAT = "u"
VIEW_STAT = "v"
RETRIEVE_STAT = "r"
DOWNLOAD_STAT = "d"
PUBLISH_STAT = "p"
INGEST_STAT = "i"
DELETE_STAT = "e"

STAT_LABELS = {UPDATE_STAT: "update", VIEW_STAT: "view", RETRIEVE_STAT: "retrieve", \
    DOWNLOAD_STAT: "download", PUBLISH_STAT: "publish", INGEST_STAT: "ingest", DELETE_STAT: "delete"}
VISIBLE_STATS = [UPDATE_STAT, VIEW_STAT, RETRIEVE_STAT, DOWNLOAD_STAT]
    
# Setup logging support.
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(LOG_HANDLER)


def saveLRStats(resource, action, request=None): 
    """
    Saves the actions on a resource.
    
    Takes into account the session to avoid to increment more than one time the
    stats counter. Returns whether the stats counter was incremented or not.