/*jshint esversion: 6 */

var creepsHelper = require('utils.creepsHelper');

function _getNewNameForRole(roleName) {
    var creepIds = creepsHelper.getCreepsInRole(roleName)
        .map((creep) => creep.name)
        .map(_getIdFromName)
        .sort(function(a, b) {
            return a < b; // desc
        });
    var maxId = creepIds[0];

    return roleName + '_' + (maxId+1);
}

function _getIdFromName(creepName) {
    if (creepName.indexOf('_') === -1) {
        return -1;
    }

    try {
        var nameParts = creepName.split('_');
        var idString = nameParts[1];
        if (idString === 'NaN') {
            idString = "-1";
        }
        var id = parseInt(idString);
        return id;
    } catch (e) {
        console.log('ERROR: unable to parse creepId from his name ' + creepName + '. Exception: ${e}');
        return -1;
    }
}

var bodyCost = [
    { part: MOVE, cost: 50 },
    { part: WORK, cost: 100 },
    { part: CARRY, cost: 50 },
    { part: ATTACK, cost: 80 },
    { part: RANGED_ATTACK, cost: 150 },
    { part: HEAL, cost: 250 },
    { part: CLAIM, cost: 600 },
    { part: TOUGH, cost: 10 }
];

function _calculateBodyCost(bodyParts) {
    function _filter(bc) { return bc.part === part; }

    var cost = 0;
    for (var i = 0; i < bodyParts.length; i++) {
        var part = bodyParts[i];
        var bodyCostItem = bodyCost.filter(_filter)[0];
        cost += bodyCostItem.cost;
    }

    return cost;
}

module.exports = {
    getNewNameForRole: _getNewNameForRole,
    calculateBodyCost: _calculateBodyCost
};

@@ -106,24 +106,45 @@
 roleName) %7B%0A
+    var number = 1;%0A%0A
     var cree
@@ -339,17 +339,52 @@
     
-var maxId
+if (creepsIds.length !== 0) %7B%0A        number
  = c
@@ -393,17 +393,27 @@
 epIds%5B0%5D
-;
+ + 1;%0A    %7D
 %0A%0A    re
@@ -438,17 +438,14 @@
 ' + 
-(maxId+1)
+number
 ;%0A%7D%0A
@@ -490,126 +490,129 @@
     
-if (creepName.indexOf('_') === -1) %7B%0A        return -1;%0A    %7D%0A%0A    try %7B%0A        var nameParts = creepName.split('_');
+try %7B%0A        var nameParts = creepName.split('_');%0A        if (nameParts.length !== 2) %7B%0A            return 0%0A        %7D%0A
 %0A   
@@ -675,16 +675,41 @@
 == 'NaN'
+ %7C%7C idString.length === 0
 ) %7B%0A    
@@ -728,18 +728,17 @@
 ring = %22
--1
+0
 %22;%0A     
@@ -916,13 +916,13 @@
 on: 
-$%7Be%7D'
+' + e
 );%0A 
@@ -939,10 +939,9 @@
 urn 
--1
+0
 ;%0A  

Fix name generator