/**
 * 聊天组模型。
 */
"use strict";

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var MODEL_EVENTS = require('../include/commons').MODEL_EVENTS;
var CONTENT_TYPES = require('../include/commons').CONTENT_TYPE;
var PLATFORMS = require('../include/commons').PLATFORM;


var log = require("../util/log.js");
var modelUtil = require('../util/modelUtil');
var getui = require('getui');

var userRepo = require('../repository/doctor.repo.js');
var groupRepo = require('../repository/group.msg.repo');
var gmRepo = require('../repository/group.msg.repo');
var nmRepo = require("../repository/notify.msg.repo");
var statsRepo = require("../repository/stats.msg.repo");
var objectUtil = require("../util/objectUtil.js");

function GroupMessage(){
    EventEmitter.call(this);
}

/**
 * 发送消息。
 *
 * @param message
 */
GroupMessage.prototype.sendMessage = function(message){
    var self = this;

    groupRepo.isGroupMember(message.group, message.groupType, message.from, function (err, result) {
        if (err) {
            modelUtil.emitDbError(self, 'Check group member failed', err);
            return;
        }

        if (result.length == 0) {
            self.emit(MODEL_EVENTS.DataNotFound, {message: 'Member with id "' + message.from + '" is not in group "' + message.group + '"'});
            return;
        }

        gmRepo.save(message.from, message.group, message.at, message.contentType, message.content, function (err, insertedRow) {
            if (err) {
                modelUtil.emitDbError(self, 'Save group message failed', err);
                return;
            }

            gmRepo.findOneMessage(insertedRow.insertId, function (err, groupMsg) {
                if (err) {
                    modelUtil.emitDbError(self, "Save group message success, but return this message failed", err);
                    return;
                }

                // 返回新增加的消息，控制器可结束网络连接
                self.emit(MODEL_EVENTS.OK, fillMessages(groupMsg));
            });

            // 更新组内统计信息, 推送通知消息给群组成员
            statsRepo.updateGroupChatSummary(message.from, message.group, message.from, 0, message.contentType, message.content, false, function (err, result) {
                if (err) modelUtil.emitDbError(null, err);
            });

            groupRepo.getMembers(message.group, message.groupType, function (err, members) {
                if (err) {
                    modelUtil.emitDbError(self, 'Get group members failed: ', err);
                    return;
                }

                if (members.length == 0) {
                    log.warn('No members in group ', message.group,
                        message.groupType === GROUP_TYPE.AdminTeam ? " of admin team." : "of discussion group.");

                    return;
                }

                // 逐个推送通知
                for (var i = 0; i < members.length; i++) {
                    var member = members[i];
                    if (member.user_id === message.from){
                        continue;
                    }

                    (function (user_id) {
                        userRepo.getUserStatus(user_id, function (err, result) {
                            if (err) {
                                console.error('Get group member status failed: ', err);
                                return;
                            }

                            var title = '';
                            var content = '';
                            if (message.contentType === CONTENT_TYPES.PlainText) {
                                title = '群组消息';
                                content = message.content;
                            } else if (message.contentType === CONTENT_TYPES.Image) {
                                title = '群组消息';
                                content = '[图片]';
                            } else if (message.contentType === CONTENT_TYPES.Audio) {
                                title = '群组消息';
                                content = '[语音]';
                            } else {
                                title = '群组消息';
                                content = '接收到一条新消息';
                            }

                            var isOnline = result.length > 0 && result[0].is_online === 1;
                            var notifyMessage = JSON.stringify({type: 'group_msg', gid: message.group});

                            // 发送并保存通知到数据库中
                            if (isOnline) {
                                var userStatus = result[0];
                                if (userStatus.platform === PLATFORMS.iOS) {
                                    getui.pushAPN(user_id,
                                        userStatus.token,
                                        message.contentType,
                                        title,
                                        content,
                                        notifyMessage,
                                        function (err, result) {
                                            err != null ? console.error(err) : console.log(result);

                                            // 这段代码重复
                                            nmRepo.save(user_id,
                                                message.contentType,
                                                title,
                                                content,
                                                notifyMessage,
                                                err != null ? 0 : 1,
                                                function (err, result) {
                                                    if (err) {
                                                        console.log('Save group notify message failed: ', err);
                                                    } else {

                                                    }
                                                });
                                        });
                                } else if (userStatus.platform === PLATFORMS.Android) {
                                    getui.pushAndroid(data.client_id,
                                        message.contentType,
                                        title,
                                        content,
                                        notifyMessage,
                                        userStatus.status,
                                        function (err, result) {
                                            err != null ? console.error(err) : console.log(result);

                                            // 这段代码重复
                                            nmRepo.save(user_id,
                                                message.contentType,
                                                title,
                                                content,
                                                notifyMessage,
                                                err != null ? 0 : 1,
                                                function (err, result) {
                                                    if (err) {
                                                        modelUtil.logDbError('Save group notify message failed', err);
                                                    }
                                                });
                                        });
                                }
                            } else {
                                // 这段代码重复
                                nmRepo.save(user_id,
                                    message.contentType,
                                    title,
                                    content,
                                    notifyMessage,
                                    0,
                                    function (err, result) {
                                        if (err) {
                                            modelUtil.logDbError('Save group notify message failed', err);
                                        }
                                    });
                            }
                        });

                        // 统计'@'信息
                        var at = message.at == user_id ? 1 : 0;

                        statsRepo.updateGroupChatSummary(user_id,
                            message.group,
                            message.from,
                            at,
                            message.contentType,
                            message.content,
                            true,
                            function (err, result) {
                                if (err) modelUtil.logDbError('Update group chat summary failed', err);
                            });
                    })(member.user_id);
                }
            });
        });
    });
};

/**
 * 获取组消息。
 */
GroupMessage.prototype.getMessages = function (groupId, memberId) {
    gmRepo.findAllMessages(groupId, !contentType ? "1,2,3,5,6" : contentType, msgStartId, msgEndId, count, function (err, rows) {
        if (err) {
            console.log('Get group message failed: ', err);

            res.status(500).send({message: 'Get group message failed.'});
            return;
        }

        var messages = fillMessages(rows);

        // 清空统计信息
        statsRepo.clearGroupChatSummary(userId, groupId, function (err, result) {
            if (err) console.log(err);
        });

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

/**
 * 获取组内未读消息。
 * @param groupId
 */
GroupMessage.prototype.getUnreadMessages = function (groupId, memberId) {
    statsRepo.getGroupChatSummary(userId, groupId, function (err, summary) {
        if (err) {
            log.error("Get unread group messages failed: ", err);

            res.status(500).send({message: "Get unread group messages failed."});
            return;
        }

        var messages = {startId: 0, count: 0, records: []};
        if (summary.length == 0 || summary[0].new_msg_count === 0) {
            res.status(200).send(messages);
            return;
        }

        messages.count = summary[0].new_msg_count;
        gmRepo.findUnread(groupId, MAX_INT, messages.count, function (err, rows) {
            if (err) {
                log.error("Get unread group messages failed: ", err);

                res.status(500).send({message: "Get unread group messages failed."});
                return;
            }

            var messages = fillMessages(rows);

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

/**
 * 将消息的返回结果合并成JSON。
 *
 * @param rows
 *
 * @returns {startId: 0, count: 0, records: []}
 */
function fillMessages(rows) {
    var messages = {startId: rows.length > 0 ? rows[0].msg_id : '', count: rows.length, records: []};
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        var record = {
            id: row.msg_id,
            from: row.from_uid,
            contentType: row.type,
            content: row.content,
            timestamp: objectUtil.timestampToLong(row.timestamp)
        };

        if (row.to_uid !== undefined) record.to = row.to_uid;
        if (row.at_uid !== undefined) record.at = row.at_uid;

        messages.records.push(record);
    }

    return messages;
}

// This class inherits from EventEmitter and expose class
util.inherits(GroupMessage, EventEmitter);
module.exports = GroupMessage;