'use strict';

var GeTui = require('./GT.push');
var Target = require('./getui/Target');

var APNTemplate = require('./getui/template/APNTemplate');
var BaseTemplate = require('./getui/template/BaseTemplate');
var APNPayload = require('./payload/APNPayload');
var DictionaryAlertMsg = require('./payload/DictionaryAlertMsg');
var SimpleAlertMsg = require('./payload/SimpleAlertMsg');
var NotyPopLoadTemplate = require('./getui/template/NotyPopLoadTemplate');
var LinkTemplate = require('./getui/template/LinkTemplate');
var NotificationTemplate = require('./getui/template/NotificationTemplate');
var PopupTransmissionTemplate = require('./getui/template/PopupTransmissionTemplate');
var TransmissionTemplate = require('./getui/template/TransmissionTemplate');

var SingleMessage = require('./getui/message/SingleMessage');
var AppMessage = require('./getui/message/AppMessage');
var ListMessage = require('./getui/message/ListMessage');

var configFile = require('../../include/commons').CONFIG_FILE;
var config = require('../../resources/config/' + configFile);

var msgStat = require('../../repository/stats.msg.repo');

var gt = new GeTui(config.geTuiConfig.HOST, config.geTuiConfig.APPKEY, config.geTuiConfig.MASTERSECRET);
var gt_appstore = new GeTui(config.geTuiAppStoreCfg.HOST, config.geTuiAppStoreCfg.APPKEY, config.geTuiAppStoreCfg.MASTERSECRET);

//test
var test = false;
if (test) {
    pushAPN('D2016082409','D503F7FCAD88E2268D1094BBC344A6218BE479BB441199555758FD5174ABEB02',1,'1','2','',function(err, result){
        if (err) {
            console.log(err);
            return;
        }
        console.log(result);
    });
}
//test end

function pushAPN(userid, token, type, title, msg, data, handler) {
    //APN简单推送
    var template = new APNTemplate();
    var payload = new APNPayload();

    msgStat.getBadgeNumber(userid, function(err, result) {
        try {
            var alertMsg = new SimpleAlertMsg();
            alertMsg.alertMsg = msg;
            payload.alertMsg = alertMsg;
            payload.badge = result;
            payload.contentAvailable = 1;
            payload.category = type;
            payload.customMsg.payload1 = data;
            template.setApnInfo(payload);

            var message = new SingleMessage();
            message.setData(template);

            //推送给企业版App
            gt.pushAPNMessageToSingle(config.geTuiConfig.APPID, token, message, function (err, res) {
                handler(err, res);
            });

            //推送给AppStore版App
            gt_appstore.pushAPNMessageToSingle(config.geTuiAppStoreCfg.APPID, token, message, function (err, res) {
                handler(err, res);
            });
        } catch (e) {
            console.log('pushAPN error:' + e);
        }
    });
}

function pushAndroid(clientid, type, title, msg, data, status, handler) {
    if (status != 1) {
        pushAndroidNotify(clientid, type, title, msg, data, handler);
    }
    pushAndroidTransmission(clientid, type, title, msg, data, handler);
}

function pushAndroidNotify(clientid, type, title, msg, data, handler) {
    var transmissionContent = {
        pushtype: 'notify',
        data: data
    }
    var template = new NotificationTemplate({
        appId: config.geTuiConfig.APPID,
        appKey: config.geTuiConfig.APPKEY,
        title: title,
        text: msg,
        logo: '',
        isRing: true,
        isVibrate: true,
        isClearable: true,
        transmissionType: 1,
        transmissionContent: JSON.stringify(transmissionContent)
    });

    //个推信息体
    var message = new SingleMessage({
        isOffline: true,                        //是否离线
        offlineExpireTime: 3600 * 12 * 1000,    //离线时间
        data: template,                          //设置推送消息类型
        pushNetWorkType: 0                     //是否wifi ，0不限，1wifi
    });

    //接收方
    var target = new Target({
        appId: config.geTuiConfig.APPID,
        clientId: clientid
    });

    gt.pushMessageToSingle(message, target, function (err, res) {
        if (err != null && err.exception != null && err.exception instanceof  RequestError) {
            var requestId = err.exception.requestId;
            console.log(err.exception.requestId);
            gt.pushMessageToSingle(message, target, requestId, function (err, res) {
                //console.log(err);
                handler(err, res);
            });
        } else {
            handler(err, res);
        }
    });
}

function pushAndroidTransmission(clientid, type, title, msg, data, handler) {
    var transmissionContent = {
        pushtype: 'transmission',
        data: data
    }

    var template =  new TransmissionTemplate({
        appId: config.geTuiConfig.APPID,
        appKey: config.geTuiConfig.APPKEY,
        transmissionType: 2,
        transmissionContent: JSON.stringify(transmissionContent)
    });

    //个推信息体
    var message = new SingleMessage({
        isOffline: true,                        //是否离线
        offlineExpireTime: 3600 * 12 * 1000,    //离线时间
        data: template,                          //设置推送消息类型
        pushNetWorkType: 0                     //是否wifi ，0不限，1wifi
    });

    //接收方
    var target = new Target({
        appId: config.geTuiConfig.APPID,
        clientId: clientid
    });

    gt.pushMessageToSingle(message, target, function (err, res) {
        console.log(res);
        if (err != null && err.exception != null && err.exception instanceof  RequestError) {
            var requestId = err.exception.requestId;
            console.log(err.exception.requestId);
            gt.pushMessageToSingle(message, target, requestId, function (err, res) {
                console.log(err);
                //handler(err, res);
            });
        } else {
            //handler(err, res);
        }
    });
}

module.exports.pushAPN = pushAPN;
module.exports.pushAndroid = pushAndroid;