use strict;
use vars qw($VERSION %IRSSI);
use Irssi;
use utf8;

$VERSION = '0.4.1';
%IRSSI = (
  authors     => 'Toyoyo',
  contact     => 'toyoyo@wirefull.org',
  name        => 'incoming_replace',
  description => 'avoid breaking terminals on UTF-8 sequences.',
  license     => 'WTFPL',
  changed     => 'Thu 19 Dec 2019 01:02:35 AM CET',
);

# @_[0]: server, @_[1]: msg, @_[4]: target
sub incoming_replace {
  if(utf8::decode(@_[1])) {
    # U+FE0F, breaks kitty, tmux, irssi, probably the universe
    @_[1] =~ s/\x{FE0F}//g;

    # Whatever.... mainly for U+B4 who breaks kitty.
    # U+60 seems to work fine, because wtf.
    @_[1] =~ s/\x{B4}/’/g;
    @_[1] =~ s/\x{60}/‘/g;

    # U+A8, Diaeresis, fails with the irssi+tmux combo, and only here.
    @_[1] =~ s/\x{A8}/¯/g;

    # Used by some japanese emoticons, fails when not combined
    @_[1] =~ s/\x{02d8}/^/g;

    # this now works
    # @_[1] =~ s/\x{0300}/‘/g;
    # @_[1] =~ s/\x{0301}/’/g;

    # Regional indicators, breaks kitty at least
    @_[1] =~ tr/🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿/🅰🅱🅲🅳🅴🅵🅶🅷🅸🅹🅺🅻🅼🅽🅾🅿🆀🆁🆂🆃🆄🆅🆆🆇🆈🆉/;
    utf8::encode(@_[1]);
  }

  # Stay tuned for the next episode!
  # To my surprise, fitzpatrick scale sequences seems to work.

  &Irssi::signal_continue(@_);
}

# We should catch everything, except the input line.
Irssi::signal_add("message public", 'incoming_replace');
Irssi::signal_add("message own_public", 'incoming_replace');
Irssi::signal_add("message irc action", 'incoming_replace');
Irssi::signal_add("message irc own_action", 'incoming_replace');
Irssi::signal_add("message private", 'incoming_replace');
Irssi::signal_add("message own_private", 'incoming_replace');
