package Devscripts::Uscan::WatchSource::Transform;

use Moo::Role;
use Devscripts::Uscan::Output;

use constant {
    ANY_VERSION => '(?:[-_]?[Vv]?(\d[\-+\.:\~\da-zA-Z]*))',
    ARCHIVE_EXT =>
      '(?i)(?:\.(?:tar\.xz|tar\.bz2|tar\.gz|tar\.zstd?|zip|tgz|tbz|txz))',
    DEB_EXT => '(?:[\+~](debian|dfsg|ds|deb)(\.)?(\d+)?$)',
};
use constant SIGNATURE_EXT => ARCHIVE_EXT . '(?:\.(?:asc|pgp|gpg|sig|sign))';

sub transformWatchSource {
    my ($self, $args) = @_;

    foreach my $watchSource (@{ $self->watchOptions }) {

        # TODO: insert here templates

        foreach my $k (keys %$watchSource) {
            # Handle @PACKAGE@ @ANY_VERSION@ @ARCHIVE_EXT@ substitutions
            $watchSource->{$k} =~ s/\@PACKAGE\@/$args->{package}/g;
            $watchSource->{$k} =~ s/\@ANY_VERSION\@/ANY_VERSION/ge;
            $watchSource->{$k} =~ s/\@ARCHIVE_EXT\@/ARCHIVE_EXT/ge;
            $watchSource->{$k} =~ s/\@SIGNATURE_EXT\@/SIGNATURE_EXT/ge;
            $watchSource->{$k} =~ s/\@DEB_EXT\@/DEB_EXT/ge;
        }

        # When global "Version-Schema" is "checksum", the main watch source has
        # to be "group"
        if (    $watchSource->{versionschema}
            and $watchSource->{versionschema} eq 'checksum'
            and !$watchSource->{component}) {
            $watchSource->{versionschema} = 'group';
        }
    }
}

1;
