package PZ::Controller::Shortcut;
use Mojo::Base 'Mojolicious::Controller', -signatures;

use Data::Validate::URI qw(is_uri);
use Image::PNG::QRCode 'qrpng';

sub redirect ($c) {
    my $shortcut = $c->schema->resultset('Shortcut')->search({
        shortcut  => $c->stash->{shortcut},
        is_active => 1,
        deleted   => undef,
    })->first;

    if ( ! $shortcut ) {
        $c->render( status => 404, text => 'not found' );
        return;
    }

    $c->res->code($shortcut->code);
    $c->redirect_to($shortcut->url);
}

sub create ($c) {
    my $url = $c->param('url');

    if( ! is_uri($url) ) {
        $c->render('shortcut/invalid', error => 'Chybná URL adresa!');
        return;
    }

    my $custom = lc($c->param('shortcut'));

    if ( ! $custom =~ /^[a..z0..9]{1,8}$/i ) {
        $c->render('shortcut/invalid', error => 'Neplatná zkratka');
        return;
    }

    if ( $custom ) {
        my $exists = $c->schema->resultset('Shortcut')->search({
            is_active => 1,
            deleted   => undef,
            shortcut  => $custom,
        })->count;

        if( $exists ) {
            $c->render('shortcut/invalid', error => "Zkratka $custom už je použitá");
            return;
        }
    }

    my %data = (
        deleted => undef,
        url     => $url,
    );

    my $shortcut = $c->current_user->shortcuts(\%data)->first;

    if ( ! $shortcut ) {
        $data{shortcut} = $custom || $c->schema->resultset('Shortcut')->generate();
        $shortcut = $c->current_user->add_to_shortcuts(\%data);
    }

    $c->render('shortcut/created',
        url => 'https://' . $c->config->{domain} . '/' . $shortcut->shortcut,
        shortcut => $shortcut
     );
}


sub qr ($c) {
    my $url = 'https://' . $c->config->{domain} . '/' . $c->stash->{shortcut};
    my $png = qrpng (text => $url, level => 4);
    $c->res->headers->content_type('image/png');
    $c->render( data => $png );
}


sub list ($c) {
    my @shortcuts = ();

    SHORTCUT:
    foreach my $shortcut ( $c->stash->{user}->shortcuts({ deleted => undef }) ) {
        push @shortcuts, $c->spec_filter(
            { $shortcut->get_columns }, 'Shortcut'
        );
    }

    $c->render(json =>  \@shortcuts,  );
}

sub update ($c) {

    my $shortcut = $c->stash->{user}->shortcuts({
        id => $c->stash->{id}
    })->first;

    if ( ! $shortcut ) {
        $c->render( status => 404, text => 'not found' );
        return;
    }

    $shortcut->update({
        code => $c->req->json->{code},
        url  => $c->req->json->{url},
    });

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

sub delete ($c) {

    my $shortcut = $c->stash->{user}->shortcuts({
        id => $c->stash->{id}
    })->first;

    if ( ! $shortcut ) {
        $c->render( status => 404, text => 'not found' );
        return;
    }

    $shortcut->update({
        deleted => \'now()'
    });

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

1;