/*
 * Made By Helcel
 */

/**
 * Script  : PhantomDiscRole.js
 * Purpose : Gives roles based on reactions....
 */
 (function() {
    var messageId = $.getSetIniDbString('discordSettings', 'selectRole', '! Select your Role !'),
        channelName = $.getSetIniDbString('discordSettings', 'roleChannel', ''),
        notInit = false;

    var Snowflake = Packages.discord4j.common.util.Snowflake,
        ReactionEmoji = Packages.discord4j.core.object.reaction.ReactionEmoji,
        Permission = Packages.discord4j.rest.util.Permission; //core.object.util.Permission;

    $.bind('webPanelSocketUpdate', function(event) {
        if (event.getScript().equalsIgnoreCase('./discord/custom/phantomDiscRoles.js')) {
            messageId = $.getIniDbString('discordSettings', 'selectRole', '! Select your Role !');
            channelName = $.getIniDbString('discordSettings', 'roleChannel', '');
        }
    });

    $.bind('discordMessageReaction', function(event) {
        var reactionEvent = event.getEvent();
        var reactionChannel = reactionEvent.getChannel().block();
        var reactionEmoji = reactionEvent.emoji;
        var reactionMessage = reactionEvent.getMessage().block();
        var reactionMessageText = reactionMessage.getContent();
        var reactionUser = reactionEvent.getUserId();

        if(!reactionMessage.getAuthorAsMember().block().getHighestRole().block().getPermissions().contains(Permission.ADMINISTRATOR)) return;
        if(reactionMessageText.indexOf(messageId)!=0) return;

        var mapping = reactionMessageText.replace(messageId,"").split("\n")
        var mojirole = {}
        for(var i = 0; i < mapping.length; ++i){
                var map = mapping[i]
                if(map.length()<3) continue;
                var mape = map.split(" ");
                if(mape.length!=2) continue;
                var clean = mape[0].substring(mape[0].lastIndexOf(':')+1).replace('>','');
                mojirole[clean] = mape[1].replace("<@&",'').replace(">",'');

                if(notInit){
                        reactionMessage.addReaction(ReactionEmoji.unicode(clean)).block();
                }
        }
        notInit = false;
        var mojiid = reactionEmoji.asUnicodeEmoji().isPresent()? (reactionEmoji.asUnicodeEmoji().get().getRaw()) : (reactionEmoji.asCustomEmoji().get().getId().asString());
        if(mojirole[mojiid]){
                var roleid = Snowflake.of(mojirole[mojiid])
                if(event.type.ordinal())
                        reactionEvent.getUser().block().asMember(reactionEvent.getGuildId().get()).block().removeRole(roleid).block()
                else
                        reactionEvent.getUser().block().asMember(reactionEvent.getGuildId().get()).block().addRole(roleid).block()
        }else{
                reactionMessage.removeReaction(reactionEmoji,reactionUser).block();
        }
    });

    $.bind('initReady', function() {});
})();
