use strict;
use vars qw($VERSION %IRSSI);
use Irssi;
use Text::CSV;
use List::Util 'first';

$VERSION = '0.2.0';
%IRSSI = (
    authors     => 'Toyoyo',
    contact     => 'toyoyo@wirefull.org',
    name        => 'twitch_msgtags',
    description => 'primitive handling of twitch message-tags and whispers',
    license     => 'WTFPL',
    changed     => 'Tue 16 Apr 2019 01:18:16 PM CEST',
);

# Feel free to add some sort of configuration
# I don't want to call some sort of read_settings() function on *each* received message on *all* servers
# or just edit to fit your needs

sub event_twitch {
  # we only target twitch
  if(@_[0]->{'tag'} eq 'twitch') {
    # we're using twitch 'tags' capability, commands are on third pos, not second.
    # that's precisely what's breaking irssi.
    # so, $msg_parts[2]
    my @msg_parts = split(' ' , @_[1]);

    # if we want that USERSTATE spam
    # one on *each* message, for displaying specific icons, color, whatever
    # you don't want this, really
    if ($msg_parts[2] eq "USERSTATE") {
      if(@_[1] =~ m/([^ ]+) (.*$)/) {
        @_[1] = $2;
#        my @statedata = split(' ' , $2);
#        foreach my $window (Irssi::windows()) {
#          if ($window->{name} eq 'twitch') {
#            $window->print("\x0314<\x03" . $statedata[2] . "\x0314>\x03 STATE:" . $1, MSGLEVEL_PUBLIC);
#            $window->activity(3);
#          }
#        }
      }
    }


    # if we want USERNOTICES
    # basically the reason of this script. you *might* be able to see who just gift you a sub, and you didn't notice, and he's sad
    if ($msg_parts[2] eq "USERNOTICE") {
      if(@_[1] =~ m/([^ ]+) (.*$)/) {
        @_[1] = $2;
        my @statedata = split(' ' , $2);
        foreach my $window (Irssi::windows()) {
          if ($window->{name} eq 'twitch') {
            # yeah, tags are basically CSV. and I'm lazy.
            my $csv = Text::CSV->new({sep_char => ';'});
            $csv->parse($1);
            my @fields = $csv->fields();
            my (undef, $msgid)     = split('=', (first { /msg-id/ } @fields));
            my (undef, $msglogin)  = split('=', (first { /login/ } @fields));
            my (undef, $msgsysmsg) = split('=', (first { /system-msg/ } @fields));
            $msgsysmsg =~ s/\\s/ /g;
            $msgsysmsg =~ s/\\n/ /g;

            # One-fit-all approach
            # $msgsysmsg have anything we want anyway
            # There's an example at the end of the file for specific handling
            $window->print("\x0314<\x03" . $msglogin . '@' . $statedata[2] . "\x0314>\x03 " . $msgid . ": " . $msgsysmsg, MSGLEVEL_PUBLIC);
          }
        }
      }
    }

    # our beloved whispers, since PRIVMSG was probably too... obvious? for twitch
    # they aren't even tied to a specific channel...
    # toyoyotest!toyoyotest@toyoyotest.tmi.twitch.tv WHISPER toyoyotoyo :blahblah
    # I could convert them to PRIVMSG, but we would not be able to reply anyway, since *sending* them is tied to a channel
    if ($msg_parts[2] eq "WHISPER") {
      if(@_[1] =~ m/([^ ]+) (.*$)/) {
        @_[1] = $2;
        my ($sender, $whisper_text) = ($1, $2) if @_[1] =~ m/^.*\!([^@]+).*?WHISPER.+?:(.*)$/;
        foreach my $window (Irssi::windows()) {
          if ($window->{name} eq 'twitch' && defined $sender && defined $whisper_text) {
            $window->print("\x0314<\x03 " . $sender . "\x0314>\x03 " . $whisper_text, MSGLEVEL_PUBLIC);
            $window->activity(3);
          }
        }
      }
    }

# debug mode
#    foreach my $window (Irssi::windows()) {
#      if ($window->{name} eq 'twitch') {
#        $window->print(@_[1], MSGLEVEL_PUBLIC);
#        $window->activity(3);
#      }
#    }

    if ($msg_parts[2] eq "PRIVMSG") {
      if(@_[1] =~ m/\;id=(.*?)\;/) {
        my $msg_id=$1;
        @_[1] =~ m/PRIVMSG(.*?)$/;
        my $msg_msg=$1;

        foreach my $window (Irssi::windows()) {
          if ($window->{name} eq 'twitch_dump') {
            $window->print($msg_id . $msg_msg, MSGLEVEL_PUBLIC);
            $window->activity(0);
          }
        }
      }
      @_[1] =~ s/^[^\ ]*\ //;
    }

    # any other command, we just strip the tags if they are here, get a standard IRC command, and let irssi continue
    if (@_[1] =~ m/^@/) {
      @_[1] =~ s/^[^\ ]*\ //;
    }
  }

  # whatever happened, we probably want the signal to continue.
  &Irssi::signal_continue(@_);
}

Irssi::signal_add("server incoming", 'event_twitch');

# examples of specific handling of some USERNOTICEs
#if($msgid eq 'subgift') {
#  my (undef, $msgpmonths) = split('=', (first { /msg-param-months/ } @fields));
#  my (undef, $msgprecipient) = split('=', (first { /msg-param-recipient-display-name/ } @fields));
#  $window->print("\x0314<\x03" . $statedata[2] . "\x0314>\x03 " . $msgid . ", " . $msglogin . " " . $msgpmonths . " month(s) to " . $msgprecipient . " : " . $msgsysmsg, MSGLEVEL_PUBLIC);
#}
#else {
#  my $flatfields;
#  foreach(@fields) {
#  $flatfields = $flatfields . "$_ ";
#  }
#  $window->print("\x0314<\x03" . $statedata[2] . "\x0314>\x03 unhandled " . $msgid . " : " . $flatfields, MSGLEVEL_PUBLIC);
#}
