package IdPAccountManager::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 warnings;

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

use IdPAccountManager::Data::ServiceProvider;
use IdPAccountManager::Data::ServiceProvider::Manager;

use IdPAccountManager::Tools;

use Carp;

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

sub new {
    my ($pkg, %args) = @_;

    my $self = SUPER::new->(%args);

    $self->{dev_sp_contact} = $args{dev_sp_contact};

    return $self;
}

## Print the content of a test account
sub print {
    my ($self, $fd) = @_;
    $fd = \*STDOUT unless $fd;

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

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

    my %contact_list;

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

    foreach my $contact_email (split /,/, $self->{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, $email) = @_;

    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 =
          IdPAccountManager::ServiceProvider->new(
            entityid => $persistent_sp->entityid());
        $service_provider->load();
        push @$service_providers, $service_provider;
    }

    return $service_providers;
}

1;
__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).