/**
 * 系统消息。
 */
"use strict";

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

var MODEL_EVENTS = require('../include/commons').MODEL_EVENTS;
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 smRepo = require("../repository/system.msg.repo.js");
var nmRepo = require("../repository/notify.msg.repo.js");

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

/**
 * 发送消息。
 *
 * @param message
 */
SystemMessage.prototype.send = function (message) {
    var self = this;
    userRepo.getUserStatus(message.to, function (err, rows) {
        if (err) {
            console.log("Lookup system message receiver failed: ", err);

            this.emit(MODEL_EVENTS.Error, {message: "Lookup system message receiver failed."});
            return;
        }

        if (rows.length == 0) {
            this.emit(MODEL_EVENTS.DataNotFound, {message: "User not found: " + message.to});
            return;
        }

        var userStatus = rows[0];
        var isOnline = userStatus.is_online;
        var notifyMessage = JSON.stringify({type: 'system_msg', data: message.content});

        // 保存该条推送信息
        smRepo.save(message.to,
            message.contentType,
            message.title,
            message.summary,
            message.content,
            function (err, result) {
                if (err) {
                    modelUtil.emitDbError(self, "Save system notify message failed.", err);
                    return;
                }

                // 先通知外层操作已经完成，再处理后续操作。客户可先结束网络连接，减少客户端等待。
                self.emit(MODEL_EVENTS.OK, {});

                // 保存通知到数据库中
                nmRepo.save(message.to,
                    message.contentType,
                    message.title,
                    message.summary,
                    notifyMessage,
                    isOnline,
                    function (err, result) {
                        if (err) {
                            modelUtil.logDbError("Save system notify message failed", err);
                            return;
                        }

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

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