package PiTube::Controller::Nginx;
use Mojo::Base 'Mojolicious::Controller';

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

sub callback_rtmp {
    my $c = shift;

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

        # 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 ),
        });


    }

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

sub callback_recorder {
    my $c = shift;

    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 {
    my $c = shift;

    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 => '');

}

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;