package PiTube::Controller::Nginx;

use feature 'signatures';
no warnings qw{ experimental::signatures };

use Mojo::Base 'Mojolicious::Controller';
use Mojo::Pg::PubSub;

use constant HLS => qr/hls\/([a-z0-9\-]+)(_\w+)?(\/\w+)?\.(m3u8|ts)$/i;

sub callback_rtmp($c) {
    my $pubsub = Mojo::Pg::PubSub->new(pg => $c->pg);

    if ( $c->param('call') =~ /publish/ ) {
        my $name  = $c->param('name');

        my $event = 'start';
        $event = $1 if $c->param('call') =~ /(update|done)/;

        # stream
        my $stream = $c->schema->resultset('Stream')->find({
            key => $name,
        });
        $c->render( status => 404, text => '' ), return if ! $stream;

        # kontrola tokenu
        my $user = $c->schema->resultset('User')->find({
            token => $c->param('token')
        });
        $c->render( status => 403, text => ''), return if ! $user;

#        my $acl = $c->schema->resultset('ACL')->user_acl(
#            $user->username,
#        );

        # TODO: autorizace user/stream

        # aktualizace stavu streamu
        $stream->update({
            publish_last     => '\now()',
            publish_user_id  => $user->id,
            publish_time     => ( $c->param('time') // 0 ),
            is_live          => ( $c->param('call') =~ /done/ ) ? 'f':'t',
        });

        # pri zahajeni a ukonceni vysulani smazat priznak nahravani
        if ( $event ne 'update' ) {
            $stream->update({ recording => 'f'});
        }

        $pubsub->json('streams')->notify( streams => {
            call      => $c->param('call'),
            stream_id => $stream->id,
        });
    }

    $c->render( status => 204, text => '' );
}

sub callback_recorder($c) {

    my $name = $c->param('name');

    # stream
    my $stream = $c->schema->resultset('Stream')->find({
        key => $name,
    });
    $c->render( status => 404, text => '' ), return if ! $stream;

    # aktualizace stavu streamu
    $stream->update({
        recording     => 'f',
    });

    my $record = $stream->records(
        {
            end  => undef,
            path => undef,
        },
        {
            order_by => {'-desc' => 'begin'}
        }
    )->first;

    if ( $record ) {
        $record->update({
            path     => $c->param('path'),
            recorder => $c->param('recorder'),
            end      => \'now()',
        });
    }

    $c->render( status => 204, text => '' );
}

sub callback_hls($c) {

    my $code = 403;

    $c->app->log->error($c->req->headers->to_string);

    if ($c->req->headers->header('X-Original-URI') =~ HLS ) {

$c->app->log->error('>>>>>>>>>>>>'. $1
);
        if ( $c->session->{user} ) {
            $code = 204 if $c->session->{user}{acl}{ $1 } & 4;
        }
        else {
            my $is_public = $c->schema->resultset('Stream')->count({
                key => $1, is_public => 't'
            });
            $code = 204 if $is_public;
        }
    }

    $c->render( status => $code, text => '');
}

sub callback_record {
    my $c = shift;

    $c->app->log->debug($c->req->headers->header('X-Original-URI'));

#    if ($c->req->headers->header('X-Original-URI') =~ HLS ) {
#        if ( $c->session->{user}{acl}{ $1 } & 4 ) { #TODO: constant
            $c->render( status => 204, text => '' );
#            return;
#        }
#    }

#    $c->render( status => 403, text => '');

}

1;