use strict;
use warnings;

### after: use lib qw(@RT_LIB_PATH@);
use lib qw(/opt/rt4/local/lib /opt/rt4/lib);

package RT::Extension::Assets::Test;
use base 'RT::Test';

our @EXPORT = qw(create_catalog create_asset create_assets create_cf apply_cfs);

sub import {
    my $class = shift;
    my %args  = @_;

    $args{'requires'} ||= [];
    if ( $args{'testing'} ) {
        unshift @{ $args{'requires'} }, 'RT::Extension::Assets';
    } else {
        $args{'testing'} = 'RT::Extension::Assets';
    }

    $class->SUPER::import( %args );

    require RT::Extension::Assets;
    require RT::Asset;
    __PACKAGE__->export_to_level(1);
}

sub diag {
    Test::More::diag(@_) if $ENV{TEST_VERBOSE};
}

sub create_catalog {
    my %info  = @_;
    my $catalog = RT::Catalog->new( RT->SystemUser );
    my ($id, $msg) = $catalog->Create( %info );
    if ($id) {
        diag("Created catalog #$id: " . $catalog->Name);
        return $catalog;
    } else {
        my $spec = join "/", map { "$_=$info{$_}" } keys %info;
        RT->Logger->error("Failed to create catalog ($spec): $msg");
        return;
    }
}

sub create_asset {
    my %info  = @_;
    my $asset = RT::Asset->new( RT->SystemUser );
    my ($id, $msg) = $asset->Create( %info );
    if ($id) {
        diag("Created asset #$id: " . $asset->Name);
        return $asset;
    } else {
        my $spec = join "/", map { "$_=$info{$_}" } keys %info;
        RT->Logger->error("Failed to create asset ($spec): $msg");
        return;
    }
}

sub create_assets {
    my $error = 0;
    for my $info (@_) {
        create_asset(%$info)
            or $error++;
    }
    return not $error;
}

sub create_cf {
    my %args = (
        Name        => "Test Asset CF ".($$ + rand(1024)),
        Type        => "FreeformSingle",
        LookupType  => RT::Asset->CustomFieldLookupType,
        @_,
    );
    my $cf = RT::CustomField->new( RT->SystemUser );
    my ($ok, $msg) = $cf->Create(%args);
    RT->Logger->error("Can't create CF: $msg") unless $ok;
    return $cf;
}

sub apply_cfs {
    my $success = 1;
    for my $cf (@_) {
        my ($ok, $msg) = $cf->AddToObject( RT::Catalog->new(RT->SystemUser) );
        if (not $ok) {
            RT->Logger->error("Couldn't apply CF: $msg");
            $success = 0;
        }
    }
    return $success;
}

1;
