#!/usr/bin/perl -w

use strict;
use FindBin;
use Module::Pluggable search_path => ['Display::Plugins'];
use Clutter qw( :init );
use Glib;
use POE qw(Loop::Glib);
use Getopt::Long;

use lib "$FindBin::Bin/lib";

use Display::Config;
use Display::Notifications;

my $full_screen = 1;

GetOptions(
  'full|f!' => \$full_screen,
);

my $session = POE::Session->create (
  inline_states => {
    _start =>  \&start,
  },
);

$poe_kernel->run;

#Clutter->main();

sub start {
  my ( $kernel, $session ) = @_[ KERNEL, SESSION ];

  $kernel->alias_set('display');

  my $stage = Clutter::Stage->get_default();
  $stage->set_color(Clutter::Color->parse('Black'));
  $stage->signal_connect('key-press-event' => sub { exit; });

  if ($full_screen) {
    $stage->fullscreen;
  } else {
    $stage->set_size(800, 600);
  }

  my $config = Display::Config->new();
  my $notifications = Display::Notifications->new($kernel, $session, $stage);

  my @modules = loadModules($kernel, $session, $stage, $config, $notifications);

  $stage->show_all();
}


my @modules;
sub loadModules {
  my ($kernel, $session, $stage, $config, $notifications) = @_;

  my @plugins = plugins();
  if (defined $config->{_config}{'background'}) {
    warn "background module is set\n";
    warn "Considering background: " . join(", ", grep /$config->{_config}{'background'}/, @plugins) . "\n";
    load_plugin($kernel, $session, $stage, $config, $notifications, grep /$config->{_config}{'background'}/, @plugins );
  }

  for my $module (@{ $config->{_config}{'enabled'} }) {
    warn "Considering $module: " . join(", ", grep /$module/, @plugins) . "\n";
    load_plugin($kernel, $session, $stage, $config, $notifications, grep /$module/, @plugins);
  }
}

sub load_plugin {
  my ($kernel, $session, $stage, $config, $notifications, @plugin) = @_;

  for my $module (@plugin) {
    eval "use $module";
    if ($@) {
      warn "Failed to load plugin: $module ($@)\n";
    } else {
      push @modules, $module->new($kernel, $session, $stage, $config, $notifications);
    }
  }
} 

sub linear {
  my $alpha    = shift;
  my $timeline = $alpha->get_timeline();

  return int($timeline->get_progress() * Clutter::Alpha->MAX_ALPHA);
}

sub smoothstep_dec {
  return Clutter::Alpha->smoothstep_dec($_[0]);
}
sub smoothstep_inc {
  return Clutter::Alpha->smoothstep_inc($_[0]);
}

