package App::MPD::Feeder;

use strict;
use warnings;
use utf8;
use feature 'state';

use App::MPD::Feeder::Options;
use App::MPD::Feeder::DB;
use DBD::Pg;
use DBI;
use Getopt::Long;
use IO::Async::Signal;
use Log::Any qw($log);
use Net::Async::MPD;
use Object::Pad;
use Syntax::Keyword::Try;


class App::MPD::Feeder {
    has $cfg_file :reader;
    has $opt :reader;
    has $db :reader;
    has $db_needs_update :writer = 1;
    has $mpd :reader;

use constant DEFAULT_CONFIG_FILE => '/etc/mpd-feeder/mpd-feeder.conf';

    ADJUST {
        Getopt::Long::Configure('pass_through');
        Getopt::Long::GetOptions('cfg|config=s' => \$cfg_file);
        Getopt::Long::Configure('no_pass_through');

        $cfg_file //= DEFAULT_CONFIG_FILE if -e DEFAULT_CONFIG_FILE;

        $self->configure;

        $db_needs_update = 0 if $opt->skip_db_update;
    }

    method configure {
        my $new_opt = App::MPD::Feeder::Options->new;

        $new_opt->parse_config_file($cfg_file) if $cfg_file;

        $new_opt->parse_command_line;

        Log::Any::Adapter->set( Stderr => log_level => $new_opt->log_level );

        $opt = $new_opt;

        $db = App::MPD::Feeder::DB->new( opt => $opt );
    }

    method connect_mpd {
        return if $mpd;

        my %conn = ( auto_connect => 1 );
        $conn{host} = $opt->mpd_host if $opt->mpd_host;
        $conn{port} = $opt->mpd_port if $opt->mpd_port;

        $mpd = Net::Async::MPD->new(%conn);

        $mpd->on(
            close => sub {
                die "Connection to MPD lost";
            }
        );

        my $int_signal_handler = sub {
            state $signal_count = 0;
            $signal_count++;
            $log->debug("Signal received. Stopping loop");
            $mpd->loop->stop('quit');

            if ( $signal_count > 1 ) {
                $log->warn("Another signal received (#$signal_count)");
                $log->warn("Exiting abruptly");
                exit 2;
            }
        };

        for (qw(TERM INT)) {
            $mpd->loop->add(
                IO::Async::Signal->new(
                    name       => $_,
                    on_receipt => $int_signal_handler,
                )
            );
        }

        $mpd->loop->add(
            IO::Async::Signal->new(
                name       => 'HUP',
                on_receipt => sub {
                    $log->debug("SIGHUP received. Scheduling reload");
                    $mpd->loop->stop('reload');
                },
            )
        );

        $mpd->loop->add(
            IO::Async::Signal->new(
                name       => 'USR1',
                on_receipt => sub {
                    $log->debug("SIGUSR1 received. Dumping configuration to STDERR");
                    my $old = select \*STDERR;
                    try {
                        $opt->dump;
                    }
                    finally {
                        select $old;
                    }
                },
            )
        );
    }

    method connect_db {
        $db->connect($opt);
        $self->update_db;
    }

    method update_db($force = undef) {
        if (!$db_needs_update and !$force) {
            $log->debug("Skipping DB update");
            return;
        }

        $log->info('Updating song database');
        $self->connect_mpd;

        my $rows = $mpd->send('listallinfo')->get;

        $db->start_update;
        try {
            my $song_count;

            foreach my $entry (@$rows) {
                next unless exists $entry->{file};

                $self->db->store_song( $entry->{file},
                    $entry->{AlbumArtist} // $entry->{Artist},
                    $entry->{Album} );
                $song_count++;
            }

            $log->info("Updated data about $song_count songs");

            $self->db->remove_stale_entries;

            $self->db->finish_update;

            $db_needs_update = 0;
        }
        catch {
            my $err = $@;
            $self->db->cancel_update;
            die $err;
        }
    }

    method queue_songs($num = undef, $callback = undef) {
        $self->connect_db;
        if (!defined $num) {
            $self->connect_mpd;
            $mpd->send('playlist')->on_done(
                sub {
                    my $present = scalar @{ $_[0] };

                    $log->notice( "Playlist contains $present songs. Wanted: "
                            . $opt->target_queue_length );
                    if ( $present < $opt->target_queue_length ) {
                        $self->queue_songs(
                            $opt->target_queue_length - $present, $callback );
                    }
                    else {
                        $callback->() if $callback;
                    }
                }
            );

            return;
        }

        my @list = $self->db->find_suitable_songs($num);

        die "Found no suitable songs" unless @list;

        if ( @list < $num ) {
            $log->warn(
                sprintf(
                    'Found only %d suitable songs instead of %d',
                    scalar(@list), $num
                )
            );
        }

        $log->info("About to add $num songs to the playlist");

        my @paths;
        for my $song (@list) {
            my $path = $song->{song};
            $path =~ s/"/\\"/g;
            push @paths, $path;
        }

        $log->debug( "Adding " . join( ', ', map {"«$_»"} @paths ) );
        # MPD needs raw bytes
        utf8::encode($_) for @paths;
        my @commands;
        for (@paths) {
            push @commands, [ add => "\"$_\"" ];
        }
        $self->connect_mpd;
        my $f = $mpd->send( \@commands );
        $f->on_fail( sub { die @_ } );
        $f->on_done(
            sub {
                $self->db->note_song_qeued($_) for @list;
                $callback->(@_) if $callback;
            }
        );
    }

    method prepare_to_wait_idle {
        $log->trace('declaring idle mode');
        $mpd->send('idle database playlist')->on_done(
            sub {
                my $result = shift;

                if ( $result->{changed} eq 'database' ) {
                    $db_needs_update = 1;
                    $self->prepare_to_wait_idle;
                }
                elsif ( $result->{changed} eq 'playlist' ) {
                    $self->queue_songs( undef,
                        sub { $self->prepare_to_wait_idle } );
                }
                else {
                    use JSON;
                    $log->warn(
                        "Unknown result from idle: " . to_json($result) );
                    $self->prepare_to_wait_idle;
                }
            }
        );
    }

    method run {

        $self->prepare_to_wait_idle;
    }

    method stop {
        undef $mpd;

        $db->disconnect;
    }

    method run_loop {
        $self->connect_db;

        for ( ;; ) {
            $self->queue_songs( undef, sub { $self->run } );

            $log->debug("Entering event loop. PID=$$");

            my $result = $mpd->loop->run;
            $log->trace( "Got loop result of " . ( $result // 'undef' ) );

            if ( 'reload' eq $result ) {
                $log->notice("disconnecting");
                $self->stop;

                my @exec = ( $0, '--config', $self->cfg_file, '--skip-db-update' );
                if ( $log->is_trace ) {
                    $log->trace( 'exec '
                            . join( ' ', map { /\s/ ? "'$_'" : $_ } @exec ) );
                }
                exec(@exec);
            }

            if ( 'quit' eq $result ) {
                $log->trace("quitting because of 'quit' loop result");
                $self->stop;
                exit 0;
            }
        }
    }
}

