# -*- coding: utf-8 -*-
from max.MADMax import MADMaxDB
from max.decorators import MaxResponse
from max.decorators import requireContextActor
from max.decorators import requirePersonActor
from max.models import Activity
from max.oauth2 import oauth2
from max.rest.ResourceHandlers import JSONResourceEntity
from max.rest.ResourceHandlers import JSONResourceRoot
from max.rest.utils import searchParams

from pyramid.httpexceptions import HTTPNoContent
from pyramid.view import view_config

from bson import ObjectId
from datetime import timedelta


@view_config(route_name='user_activities', request_method='GET', restricted=['Manager'])
@MaxResponse
@oauth2(['widgetcli'])
@requirePersonActor(force_own=False)
def getUserActivities(context, request):
    """
         /people/{username}/activities

         Return all activities generated by a user.
    """
    mmdb = MADMaxDB(context.db)
    query = {}
    query['actor.username'] = request.actor['username']
    query['verb'] = 'post'
    chash = request.params.get('context', None)
    if chash:
        query['contexts.hash'] = chash

    is_head = request.method == 'HEAD'
    activities = mmdb.activity.search(query, keep_private_fields=False, flatten=1, count=is_head, **searchParams(request))

    handler = JSONResourceRoot(activities, stats=is_head)
    return handler.buildResponse()


@view_config(route_name='user_activities', request_method='POST', restricted='Manager')
@MaxResponse
@oauth2(['widgetcli'])
@requirePersonActor(force_own=False)
def addAdminUserActivity(context, request):
    """
         /people|contexts/{username|hash}/activities

         Add activity impersonated as a valid MAX user or context
    """
    rest_params = {'actor': request.actor,
                   'verb': 'post'}

    # Initialize a Activity object from the request
    newactivity = Activity()
    newactivity.fromRequest(request, rest_params=rest_params)

    # Search if there's any activity from the same user with
    # the same actor in the last minute
    mmdb = MADMaxDB(context.db)
    query = {
        'actor.username': request.actor.username,
        'object.content': newactivity['object'].get('content', ''),
        'published': {'$gt': newactivity.published - timedelta(minutes=1)}
    }

    if newactivity.get('contexts', []):
        query['contexts.hash'] = {'$in': [a['hash'] for a in newactivity.contexts]}

    duplicated = mmdb.activity.search(query)

    if duplicated:
        code = 200
        newactivity = duplicated[0]
    else:
        # New activity
        code = 201
        if newactivity['object']['objectType'] == u'image' or \
           newactivity['object']['objectType'] == u'file':
            # Extract the file before saving object
            activity_file = newactivity.extract_file_from_activity()
            activity_oid = newactivity.insert()
            newactivity['_id'] = ObjectId(activity_oid)
            newactivity.process_file(request, activity_file)
            newactivity.save()
        else:
            activity_oid = newactivity.insert()
            newactivity['_id'] = activity_oid

    handler = JSONResourceEntity(newactivity.flatten(squash=['keywords']), status_code=code)
    return handler.buildResponse()


@view_config(route_name='context_activities', request_method='POST', restricted='Manager')
@MaxResponse
@oauth2(['widgetcli'])
@requireContextActor
def addAdminContextActivity(context, request):
    """
         /people|contexts/{username|hash}/activities

         Add activity impersonated as a valid MAX user or context
    """
    rest_params = {'actor': request.actor,
                   'verb': 'post'}

    # Initialize a Activity object from the request
    newactivity = Activity()
    newactivity.fromRequest(request, rest_params=rest_params)

    # Search if there's any activity from the same user with
    # the same actor in the last minute
    mmdb = MADMaxDB(context.db)
    query = {
        'actor.url': request.actor.url,
        'object.content': newactivity['object']['content'],
        'published': {'$gt': newactivity.published - timedelta(minutes=1)}
    }

    if newactivity.get('contexts', []):
        query['contexts.hash'] = {'$in': [a['hash'] for a in newactivity.contexts]}

    duplicated = mmdb.activity.search(query)

    if duplicated:
        code = 200
        newactivity = duplicated[0]
    else:
        code = 201
        activity_oid = newactivity.insert()
        newactivity['_id'] = activity_oid

    handler = JSONResourceEntity(newactivity.flatten(), status_code=code)
    return handler.buildResponse()


@view_config(route_name='activities', request_method='GET', restricted='Manager')
@MaxResponse
@oauth2(['widgetcli'])
@requirePersonActor(force_own=False, exists=False)
def getActivities(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    is_head = request.method == 'HEAD'
    activities = mmdb.activity.search({'verb': 'post'}, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(activities, stats=is_head)
    return handler.buildResponse()


@view_config(route_name='context_activities', request_method='GET', restricted='Manager')
@MaxResponse
@oauth2(['widgetcli'])
@requirePersonActor(force_own=False, exists=False)
def getContextActivities(context, request):
    """
    """
    chash = request.matchdict.get('hash', None)
    mmdb = MADMaxDB(context.db)
    is_head = request.method == 'HEAD'
    activities = mmdb.activity.search({'verb': 'post', 'contexts.hash': chash}, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(activities, stats=is_head)
    return handler.buildResponse()


@view_config(route_name='activity', request_method='DELETE', restricted='Manager')
@MaxResponse
@oauth2(['widgetcli'])
@requirePersonActor(force_own=False, exists=False)
def deleteActivity(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    activityid = request.matchdict.get('activity', None)
    found_activity = mmdb.activity[activityid]

    found_activity.delete()
    return HTTPNoContent()
