///<reference path=".#ts/client.d.ts" />

interface Templates {
	depositSuccessNotification: Template;
}

Template.depositSuccessNotification.onRendered(function(){

	this.subscribe('Banking/userAllTimeDepositCount', {});
	this.subscribe('Banking/userTransactions', {_id: this.data.options.content});

	var self = this;
	var stats = Reporting.Stats.db.findOne({
		type: Reporting.StatsType.USER,
		user: Users.Profile.active(),
		period: Reporting.Period.ALLTIME,
		tagKey: null,
		time: null
	});
	if (stats && stats.data && stats.data.depositCount > 3) {
		Meteor.setTimeout(function () {
			self.data.setRead();
		}, 4000);
	}

});

Template.depositSuccessNotification.helpers({

	tx: function() {
		return Banking.Transaction.db.findOne((<any>this).options.content);
	},

	title: function() {
		return i18n('notifications.depositSuccessTitle');
	},

	body: function() {
		return i18n('notifications.depositSuccessBody').format((<any>this).formattedAmount()) + i18n('notifications.depositSuccessBody2');
	}

});

Template.depositSuccessNotification.events({

	'click .howl-message, click .howl-close': function() {
		var deposits = Reporting.Stats.db.findOne({
			type: Reporting.StatsType.USER,
			user: Users.Profile.active(),
			period: Reporting.Period.ALLTIME,
			tagKey: null,
			time: null
		});
		var tx = Banking.Transaction.db.findOne((<any>this).options.content);
		var eventAction = deposits ? 'Deposit done' : 'First deposit done';
		googleSend({
			'eventCategory': 'Cashier',
			'eventAction': eventAction,
			'eventValue': tx.amountInMillis(),
			'pageEventArea': 'Main',
			'deposits': 1,
			'depositAmount': tx.amountInMillis(),
			'depositCount': deposits ? deposits.data.depositCount + 1 : 1,
			'depositTotal': deposits ? deposits.data.depositAmount * 1000 + tx.amountInMillis() : 0
		});

		Meteor.call('Fraud/getDeviceInfo', (err, res) => {
			if (err) {
				return;
			}
			Meteor.call('Fraud/DepositLookup', res);
		});
	},

	'click .howl-message-inner': function () {
		var deposits = Reporting.Stats.db.findOne({
			type: Reporting.StatsType.USER,
			user: Users.Profile.active(),
			period: Reporting.Period.ALLTIME,
			tagKey: null,
			time: null
		});
		var tx = Banking.Transaction.db.findOne((<any>this).options.content);

		var eventAction = deposits ? 'Deposit done' : 'First deposit done';
		googleSend({
			'eventCategory': 'Cashier',
			'eventAction': eventAction,
			'eventValue': tx.amountInMillis(),
			'pageEventArea': 'Main',
			'deposits': 1,
			'depositAmount': tx.amountInMillis(),
			'depositCount': deposits ? deposits.data.depositCount + 1 : 1,
			'depositTotal': deposits ? deposits.data.depositAmount * 1000 + tx.amountInMillis() : 0
		});

		Meteor.call('Fraud/getDeviceInfo', (err, res) => {
			if (err) {
				return;
			}
			Meteor.call('Fraud/DepositLookup', res);
		});
		if (deposits && deposits.data && deposits.data.depositCount < 4) {
			Modals.open('depositSuccessModal', {});
		}
	}
});