/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var sockjs = require('sockjs');

var log = require('oae-logger').logger('oae-activity-rest');
var OAE = require('oae-util/lib/oae');
var OaeUtil = require('oae-util/lib/util');

var ActivityAPI = require('oae-activity');
var ActivityPush = require('./internal/push');


//////////////////////
// ACTIVITY STREAMS //
//////////////////////

/**
 * Request handler to get the activity stream of the given stream ID. It will fetch the activities and send out
 * the response.
 *
 * @param  {String}    activityStreamId    The ID of the activity stream to fetch
 * @param  {Request}   req                 The express request object
 * @param  {Response}  res                 The express response object
 * @api private
 */
var _handleGetActivities = function(activityStreamId, req, res) {
    var limit = OaeUtil.getNumberParam(req.query.limit, 10, 1, 25);
    var start = req.query.start;
    ActivityAPI.getActivityStream(req.ctx, activityStreamId, 'activity', start, limit, req.query.format, function(err, activityStream) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        res.send(200, activityStream);
    });
};

/**
 * @REST getActivity
 *
 * Get the activity stream of the currently authenticated user
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /activity
 * @QueryParam  {string}            [format]            Desired format (defaults to activitystreams) [activitystreams,internal]
 * @QueryParam  {number}            [limit]             Maximum number of activities to return (defaults to 10, maximum of 25)
 * @QueryParam  {number}            [start]             Activity at which to start (defaults to 0)
 * @Return      {ActivityStream}                        Returns an object containing activity stream
 */
OAE.tenantRouter.on('get', '/api/activity', function(req, res) {
    var userId = (req.ctx.user()) ? req.ctx.user().id : null;
    _handleGetActivities(userId, req, res);
});

/**
 * @REST getActivityActivityStreamId
 *
 * Get the activity stream of the specified id
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /activity/{activityStreamId}
 * @PathParam   {string}            activityStreamId    The ID of the resource for which we want to retrieve a stream
 * @QueryParam  {string}            [format]            Desired format (defaults to activitystreams) [activitystreams,internal]
 * @QueryParam  {number}            [limit]             Maximum number of activities to return (defaults to 10, maximum of 25)
 * @QueryParam  {number}            [start]             Activity at which to start (defaults to 0)
 * @Return      {ActivityStream}                        Returns an object containing activity stream
 */
OAE.tenantRouter.on('get', '/api/activity/:activityStreamId', function(req, res) {
    _handleGetActivities(req.params.activityStreamId, req, res);
});


//////////////////////////
// NOTIFICATION STREAMS //
//////////////////////////

/**
 * @REST getNotifications
 *
 * Get the notification stream for the currently authenticated user
 *
 * @Server      tenant
 * @Method      GET
 * @Path        /notifications
 * @QueryParam  {string}            [format]            Desired format (defaults to activitystreams) [activitystreams,internal]
 * @QueryParam  {number}            [limit]             Maximum number of activities to return (defaults to 10, maximum of 25)
 * @QueryParam  {number}            [start]             Activity at which to start (defaults to 0)
 * @Return      {ActivityStream}                        Returns an object containing activity stream
 */
OAE.tenantRouter.on('get', '/api/notifications', function(req, res) {
    var limit = OaeUtil.getNumberParam(req.query.limit, 10, 1, 25);
    var userId = req.ctx.user() ? req.ctx.user().id : null;
    ActivityAPI.getActivityStream(req.ctx, userId, 'notification', req.query.start, limit, req.query.format, function(err, notificationStream) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        res.send(200, notificationStream);
    });
});

/**
 * @REST postNotificationsMarkRead
 *
 * Mark all notifications in the currently authenticated user's notification stream as read
 *
 * @Server      tenant
 * @Method      POST
 * @Path        /notifications/markRead
 * @Return      {NotificationsRead}                     Returns an object of notifications read information
 */

OAE.tenantRouter.on('post', '/api/notifications/markRead', function(req, res) {
    ActivityAPI.markNotificationsRead(req.ctx, function(err, lastReadTime) {
        if (err) {
            return res.send(err.code, err.msg);
        }

        res.send(200, JSON.stringify({'lastReadTime': lastReadTime}));
    });
});


////////////////////////
// PUSH NOTIFICATIONS //
////////////////////////


// Add websocket support
var sockjsOptions = {
    // No-op the logging
    'log': function(severity, line) {}
};
OAE.tenantServer.sockjs = sockjs.createServer(sockjsOptions);
OAE.tenantServer.sockjs.installHandlers(OAE.tenantServer.httpServer, {'prefix': '/api/push'});

/*!
 * Listen for new websocket connections
 */
OAE.tenantServer.sockjs.on('connection', ActivityPush.registerConnection);

@@ -2338,36 +2338,11 @@
     
-Returns an object containing
+The
  act
@@ -3248,36 +3248,11 @@
     
-Returns an object containing
+The
  act
@@ -4096,36 +4096,11 @@
     
-Returns an object containing
+The
  act
@@ -4874,28 +4874,25 @@
     
-Returns an object of
+Information about
  not
@@ -4910,20 +4910,8 @@
 read
- information
 %0A */

clarify return value description