angular.module('app').service('UniqueIdGenerator', function() {

    this.generateId = function(){
        var duplicateId = true;
        var newId;
        var iterations = 0;

        while(duplicateId){
            newId = baseName + randomString();
            var idFound = false;

            for(var i=0; i<allIds.length; i++){
                var id = allIds[i];
                if(id == newId){
                    idFound = true;
                    break;
                }
            }
            duplicateId = idFound;

            iterations++;
            if(iterations > 100){
                console.error("UniqueIDGenerator iterated over 100 times trying to get a new ID! This should not happen. Please check that");
                newId += Math.random().toString(16).slice(2, 4);
                break;
            }
        }

        allIds.push(newId);
        return newId;
    }

    this.removeId = function(idToRemove){
        for(var i=0; i<allIds.length; i++){
            var id = allIds[i];
            if(id == idToRemove){
                allIds.splice(i, 1);
                return;
            }
        }
    }

    function randomString() {
        return Math.random().toString(16).slice(2, 2 + hashLength);
    }

    var allIds = [];
    var baseName = 'object-';
    var hashLength = 6;

});
    