var HitDice = HitDice || (function() {
    'use strict';

    var tokenIds = [],
    configure = function() {
        if(!state.HitDice) {
            state.HitDice = {
                version: 0.1,
                config: {
                    bar: 3,
                    hitDiceAttribute: 'npc_hitdice',
                }
            };
        }
    },
    handleInput = function(msg) {
        if (msg.type === "api" && /^!mhd(\b|$)/i.test(msg.content) && playerIsGM(msg.playerid) ) {
            let who = (getObj('player',msg.playerid)||{get:()=>'API'}).get('_displayname');
            let count = 0;
            // WUSSALLTHISTHEN
            (msg.selected || [])
                .map(o=>getObj('graphic',o._id))
                .filter(g=>undefined !== g)
                .forEach( o => {
                    ++count;
                    tokenIds.push(o.id);
                    rollHitDice(o);
                })
                ;
            sendChat('',`/w "${who}" Rolling hit dice for ${count} token(s).`);
        }
    },
    findRoll = function(txt) {
        let roll = txt.match(/\d+d\d+([\+\-]\d+)?/);
        return roll ? roll[0] : 0;
    },

    rollHitDice = function(obj) {
        var sets = {},
        bar = 'bar'+state.HitDice.config.bar,
        hdAttrib,
        hdExpression = 0,
        bonus = 0
        ;

        if(_.contains(tokenIds,obj.id)){
            tokenIds=_.without(tokenIds,obj.id);

            if('graphic' === obj.get('type') &&
            'token'   === obj.get('subtype') &&
            ''        !== obj.get('represents')
            ) {
                if( obj && '' === obj.get(bar+'_link') ) {
                    hdAttrib = findObjs({
                        type: 'attribute',
                        characterid: obj.get('represents'),
                        name: state.HitDice.config.hitDiceAttribute
                    })[0];

                    if(hdAttrib) {
                        log(hdAttrib);

                        hdExpression = findRoll(hdAttrib.get('current'));
                        sendChat('','/r '+hdExpression+'+'+bonus,function(r){
                            var hp=0;
                            _.each(r,function(subr){
                                var val=JSON.parse(subr.content);
                                if(_.has(val,'total'))
                                {
                                    hp+=val.total;
                                }
                            });
                            sets[bar+"_value"] = hp||1;
                            sets[bar+"_max"] = hp||1;
                            obj.set(sets);
                        });
                    }
                }
            }
        }
    },

    saveTokenId = function(obj){
        tokenIds.push(obj.id);

        setTimeout((function(id){
            return function(){
                var token=getObj('graphic',id);
                if(token){
                    rollHitDice(token);
                }
            };
        }(obj.id)),100);
    },


    registerEventHandlers = function() {
        on('chat:message', handleInput);
        on('add:graphic', saveTokenId);
        on('change:graphic', rollHitDice);
    };

    return {
        configure: configure,
        RegisterEventHandlers: registerEventHandlers
    };

}());

on('ready',function() {
    'use strict';

    HitDice.configure();
    HitDice.RegisterEventHandlers();
});
