/**
 * Created by Sand on 2016/11/14.
 */
"use strict";

var express = require("express");
var router = express.Router();

var APIv1 = require('../include/endpoints').APIv1;

var groupRepo = require('../repository/group.repo.js');

/**
 * 获取成员头像。每个组最多返回5个成员的头像。
 *
 * 请求URL：
 *  /groups/member/avatars?groups=433,10,63
 */
router.get(APIv1.Groups.MembersAvatar, function (req, res) {
    var groups = req.query.groups;
    if (!groups) {
        throw {httpStatus: 406, message: "Missing field: groups"};
    }

    var tokens = groups.split(",");
    groups = "'" + tokens.join("', '") + "'";

    var avatars = [];
    groupRepo.getMembersAvatar(groups, function (err, members) {
        if(err){
            console.log("Get group member's avatar list failed: ", err);

            res.status(500).send({message: "Get group member's avatar list failed."});
            return;
        }

        var lastGroup;
        var lastGroupCode = '';
        for (var i = 0; i < members.length; ++i) {
            var member = members[i];
            var groupCode = member.g_code;
            if (lastGroupCode !== groupCode) {
                lastGroupCode = groupCode;
                lastGroup = {groupCode: groupCode, avatars: []};

                if(lastGroupCode !== ''){
                    avatars.push(lastGroup);
                }
            }

            lastGroup.avatars.push({
                code: member.code,
                name: member.name,
                avatar: member.photo === null ? "" : member.photo,
                role: member.type
            });
        }

        res.status(200).send(avatars);
    });
});

module.exports = router;