'use strict';

var server = require('server');
var cyborgForm = server.forms.getForm('cyborgregistrationform');

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

server.get('Start', function (req, res, next) {
    
	cyborgForm.clear();

    log.info('Form loaded.');

	res.render('cyborgTracker/registrationform', {
		cyborgForm: cyborgForm,
        disabled: false
	});

	next();
});

server.post('HandleForm', function (req, res, next) {

	
	var storageService = require('~/cartridge/scripts/storageService');
	var Transaction = require('dw/system/Transaction');
    var message = '';

    log.info('Cyborg form handler loaded.');

    Transaction.begin();
    try {

        var co = storageService.storeCyborgForm(cyborgForm);
        
        Transaction.commit();
        message = 'Form Saved';
        log.info('Cyborg form saved');
    }
    catch (e){

        Transaction.rollback();
        message = 'Failed to save';
        log.warn('Cyborg form failed to save ' + e);
    }
	
    res.render('cyborgTracker/registrationform', {
		cyborgForm: cyborgForm,
        message: message,
        disabled: true
	});

	next();
});

module.exports = server.exports();