'use strict';

var memberService = require("../services/memberService");
var memberValidator = require("../lib/memberValidator");

var newMemberHandler = (req, res) => {
    let dbError = (error) => {
        res.status(500).json({error: error});
    };

    let residentialAddress = {
        address: req.body.residentialAddress.address,
        suburb: req.body.residentialAddress.suburb,
        postcode: req.body.residentialAddress.postcode,
        state: req.body.residentialAddress.state,
        country: req.body.residentialAddress.country
    };

    let postalAddress = {
        address: req.body.postalAddress.address,
        suburb: req.body.postalAddress.suburb,
        postcode: req.body.postalAddress.postcode,
        state: req.body.postalAddress.state,
        country: req.body.postalAddress.country
    };

    let newMember = {
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        gender: req.body.gender,
        primaryPhoneNumber: req.body.primaryPhoneNumber,
        secondaryPhoneNumber: req.body.secondaryPhoneNumber,
        dateOfBirth: req.body.dateOfBirth,
        residentialAddress: residentialAddress,
        postalAddress: postalAddress
    };

    let validationErrors = memberValidator.isValid(newMember);

    if (validationErrors.length > 0) {
        return res.status(400).json({error: validationErrors});
    }

    return memberService.createMember(newMember)
        .then(() => {
            res.status(200).render('members/success', {email: req.body.email});
        })
        .catch(dbError);
};

module.exports = {
    newMemberHandler: newMemberHandler
};

@@ -568,34 +568,114 @@
 postalAddress = 
-%7B%0A
+isPostalAddressEmpty(req.body.postalAddress) ? residentialAddress :%0A        %7B%0A    
         address:
@@ -707,32 +707,36 @@
 ddress,%0A        
+    
 suburb: req.body
@@ -750,32 +750,36 @@
 Address.suburb,%0A
+    
         postcode
@@ -813,32 +813,36 @@
 stcode,%0A        
+    
 state: req.body.
@@ -862,32 +862,36 @@
 .state,%0A        
+  
+  
 country: req.bod
@@ -906,32 +906,36 @@
 Address.country%0A
+    
     %7D;%0A%0A    let 
@@ -1707,16 +1707,234 @@
 r);%0A%7D;%0A%0A
+function isPostalAddressEmpty(postalAddress)%7B%0A    return  postalAddress.address == %22%22 &&%0A            postalAddress.suburb == %22%22 &&%0A            postalAddress.postcode == %22%22 &&%0A            postalAddress.state == %22%22;%0A%7D;%0A%0A
 module.e

copies residential address if postal is blank