'use strict';

var server = require('server');

var csrfProtection = require('*/cartridge/scripts/middleware/csrf');
var userLoggedIn = require('*/cartridge/scripts/middleware/userLoggedIn');
var consentTracking = require('*/cartridge/scripts/middleware/consentTracking');

var Logger = require('dw/system/Logger');
var log = Logger.getLogger('DevTest','Notifications');

server.get('Start', 
	server.middleware.https,
	userLoggedIn.validateLoggedIn,
	consentTracking.consent,
	csrfProtection.generateToken,
	function (req, res, next) {

	var notificationsForm = server.forms.getForm('notifications');
	notificationsForm.clear();

	if(customer.profile.custom.notificationSales){
		notificationsForm.notificationSales.checked = 'checked';
	}
	if(customer.profile.custom.notificationNew){
		notificationsForm.notificationNew.checked = 'checked';
	}
	if(customer.profile.custom.notificationStock){
		notificationsForm.notificationStock.checked = 'checked';
	}

	res.render('notificationsform', {
		notificationsForm: notificationsForm
	});

    log.debug('Rendered Notifications Form');

	next();

});

server.post('HandleForm', 
	server.middleware.https, 
	csrfProtection.validateRequest, 
	function (req, res, next) {

	var notificationsForm = server.forms.getForm('notifications');

	var URLUtils = require('dw/web/URLUtils');
	var Transaction = require('dw/system/Transaction');

	Transaction.begin();
	try {

		customer.profile.custom.notificationSales = notificationsForm.notificationSales.value
		customer.profile.custom.notificationNew = notificationsForm.notificationNew.value
		customer.profile.custom.notificationStock = notificationsForm.notificationStock.value
	
		Transaction.commit();
		log.error('Saved notifications');

		var HookMgr = require('dw/system/HookMgr');
		var userEmail = customer.getProfile().getEmail();
		HookMgr.callHook('app.notification.email', 'sendNotificationsChange', userEmail);
		
	} catch (error) {
		
		Transaction.rollback();
		log.error(error);
	}

	// res.redirect( URLUtils.url('Notifications') ); //For testing
	res.redirect( URLUtils.url('Account-Show') );

	next();

})

module.exports = server.exports();