(function() {

  function sendData(tpe, d) {
    $.panelsocketserver.sendJSONToAll(JSON.stringify({
        'eventFamily': 'calert',
        'eventType': tpe,
        'data': d
    }));
  }

  $.bind('twitchFollow', function(event) {
    sendData('follow',{ 'user': event.getFollower()});
  });
  $.bind('twitchSubscriber', function(event) {
    sendData('subscribe', {
      'user': event.getSubscriber(),
      'isReSub': false,
      'months': 0,
      'tier': event.getPlan() / 1000,
      'message': event.getMessage()
    });
  });
  $.bind('twitchReSubscriber', function(event) {
    sendData('subscribe', {
      'user': event.getReSubscriber(),
      'isReSub': true,
      'months': event.getMonths(),
      'tier': event.getPlan() / 1000,
      'message': event.getMessage()
    });
  });
  $.bind('twitchSubscriptionGift', function(event) {
    sendData('gift', {
      'recipient': event.getRecipient(),
      'user': event.getUsername(),
      'months': event.getMonths(),
      'isReSub': (parseInt(event.getMonths()) > 1),
      'tier': event.getPlan() / 1000
    });
  });

  $.bind('twitchMassSubscriptionGifted', function(event) {
    sendData('mgift', {
      'user': event.getUsername(),
      'amount': event.getAmount(),
      'tier': event.getPlan() / 1000
    });
  });

  $.bind('twitchRaid', function(event) {
    sendData('raid',{
      'user': event.getUsername(),
      'viewers': event.getViewers(),
    });
  });

  $.bind('twitchBits', function (event) {
    sendData('bits', {
        'user': event.getUsername(),
        'amount': event.getBits(),
        'message': event.getMessage()
    });
  });

  $.bind('command', function(event) {
    const sender = "" + event.getSender().toLowerCase(),
        command = event.getCommand(),
        args = event.getArgs(),
        action = args[0];

    if (command.equalsIgnoreCase('calert')) {
        if (!action) {
            $.say($.whisperPrefix(sender) + $.lang.get('calert.help', ' Use "!calert [follow | subsribe | donation] user" to trigger alert.'));
        } else if (action.equalsIgnoreCase('follow')) {
          sendData('follow',{ 'user': args[1]});
        } else if (action.equalsIgnoreCase('subscribe')) {
          sendData('subscribe',{ 'user': args[1]});
        } else if (action.equalsIgnoreCase('donation')) {
          sendData('bits',{ 'user': args[1], amount: args[2]});
        } else {
            $.say($.whisperPrefix(sender) + $.lang.get('calert.help', ' Use "!calert [follow | subsribe | donation] user" to trigger alert.'));
        }
    }
});

  $.bind('initReady', function() {
    $.registerChatCommand('./custom/custom/customAlerts.js', 'calert');
    $.registerChatSubcommand('calert', 'follow', 2);
    $.registerChatSubcommand('calert', 'subscribe', 2);
    $.registerChatSubcommand('calert', 'donation', 2);
  });
})();
