package Xchat::XPI::Utils;

use strict;
use warnings;

use Xchat qw<:all>;

our $VERSION = '0.02';

my @rcolors;
BEGIN {
 if (nickcmp(get_info('version'), '2.4.0') < 0) {
  @rcolors = (3, 4, 6, 8, 9, 10, 11, 12, 13);
 } else {
  @rcolors = (19, 20, 22, 24, 25, 26, 27, 28, 29);
 }
}

sub dye_nick {
 my $nick = $_[0];
 my $col  = 0;
 $col    += ord for split //, $nick;
 return sprintf "\003%d%s", $rcolors[$col % @rcolors], $nick;
}

sub save_context {
 my $cur_cxt = get_context;
 bless \$cur_cxt, 'Xchat::XPI::Utils::ContextGuard';
}

sub local_context {
 return unless @_ >= 2;
 my $code    = pop;
 my $new_cxt = (@_ == 1) ? $_[0] : find_context(@_);
 my $cur_cxt = get_context;
 if (set_context $new_cxt) {
  my $guard = bless \$cur_cxt, 'Xchat::XPI::Utils::ContextGuard';
  return $code->();
 } else {
  return undef;
 }
}

sub Xchat::XPI::Utils::ContextGuard::DESTROY {
 set_context ${$_[0]};
}

sub called_from_script (&) {
 my $code  = shift;
 my $level = 0;
 my ($package, $filename);
 while (1) {
  my @frame = caller $level;
  last unless @frame;
  if ($frame[0] !~ /^(?:Xchat|HexChat)::XPI\b/) {
   ($package, $filename) = @frame[0, 1];
   last;
  }
  ++$level;
 }
 if (defined $filename) {
  my $internal_package = Xchat::Embed::file2pkg($filename);
  my $mock = sub { $internal_package, $package };
  no warnings 'redefine';
  local *Xchat::Embed::find_pkg   = $mock;
  local *HexChat::Embed::find_pkg = $mock;
  $code->();
 }
}

use base qw<Exporter>;

our @EXPORT         = ();
our %EXPORT_TAGS    = ('funcs' => [ qw<
 dye_nick
 save_context local_context
 called_from_script
> ]);
our @EXPORT_OK      = map { @$_ } values %EXPORT_TAGS;
$EXPORT_TAGS{'all'} = [ @EXPORT_OK ];

1;
