package IdPAccountManager::ServiceProvider;
use base 'IdPAccountManager::Data::Serviceprovider';

## Copyright (c) GEANT
## This software was developed by RENATER. The research leading to these results has received funding
## from the European Community¹s Seventh Framework Programme (FP7/2007-2013) under grant agreement nº 238875 (GÉANT).

use strict;

use IdPAccountManager::Data::Serviceprovider;
use IdPAccountManager::Data::Serviceprovider::Manager;

use IdPAccountManager::Tools;
use Conf;

require Exporter;
my @ISA    = qw(Exporter);
my @EXPORT = qw();

use Carp;

INIT {
    ## Set error mode  to non fatal
    IdPAccountManager::Data::Serviceprovider::Manager->error_mode('return');
}

## Print the content of a test account
sub print {
    my $self = shift;
    my $fd = shift || \*STDOUT;

    printf $fd
      "ServiceProvider ID=%s; entityid=%s; displayname=%s; contacts=%s\n",
      $self->id, $self->entityid, $self->displayname, $self->contacts;

    return 1.;
}

## list contacts for this SP, including those listed in conf.dev_sp_contact
sub list_contacts_as_array {
    my $self = shift;

    my %contact_list;

    foreach my $contact_email (split /,/, $self->contacts()) {
        $contact_list{$contact_email}++;
    }

    foreach my $contact_email (split /,/, $Conf::global{'dev_sp_contact'}) {
        $contact_list{$contact_email}++;
    }

    return keys %contact_list;
}

## Check if email address is a known contact (or conf.dev_sp_contact)
sub is_contact {
    my $self  = shift;
    my $email = shift;

    foreach my $known_contact ($self->list_contacts_as_array()) {
        return 1 if (lc($email) eq lc($known_contact));
    }

    return 0;
}

## list all test accounts
## Class method
sub list_service_providers {
    my %args = @_;

    my $persistent_accounts =
      IdPAccountManager::Data::Serviceprovider::Manager->get_serviceproviders(
        %args);
    my $service_providers;
    foreach my $persistent_sp (@{$persistent_accounts}) {
        my $service_provider =
          new IdPAccountManager::ServiceProvider(
            entityid => $persistent_sp->entityid());
        $service_provider->load();
        push @$service_providers, $service_provider;
    }

    return $service_providers;
}

1;    # Magic true value required at end of module
__END__

=head1 NAME

IdPAccountManager::ServiceProvider - Manage Service Providers for which test accounts have been requested for the Test Identity Provider

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 SUBROUTINES/METHODS

=head1 AUTHOR

Olivier Salaün (olivier.salaun@renater.fr)

=head1 LICENSE

Copyright (c) GEANT
This software was developed by RENATER. The research leading to these results has received funding
from the European Community¹s Seventh Framework Programme (FP7/2007-2013) under grant agreement nº 238875 (GÉANT).