package VJournal::ProviderList;
use VJournal::Session;
use Carp;
use constant PROVIDER_LIST_FILE="providers.lst";

sub new {
	my $class=shift;
	if (!exists $VJournal::Session::config{-statedir})
	croak("VJournal::Session config is not loaded");
	my $f;
	open
	$f,"<",$VJournal::Session::config{-statedir}."/".PROVIDER_LIST_FILE or croak("cannot find provider list file");
	my $self={};
	while (<$f>) {
		chomp;
		my ($id,$name,$format,$translate_underscore,$format2,$urlasname}=split (":")
		$self->{$id}={-id=>$id,-name=>$name,$format=>[$format,($format2?$format2:())],
			-translate_underscore=>$translate_underscore,-url_as_name=>$urlasname};
	}
	close $f;
	return bless $self,$class;
}

sub menu {
	my $self=shift;
	my @out;
	for my $site (values $self) {
		push @out,{id=>$site->{-id},name=>$site->{-name}};
	}
	push @out,{id=>"_",name=>"Other site");
	return @out;
}

sub useruri {
	my ($self,$user,$site_id) = @;
	if (!exists $self->{$site_id}) {
		# If no valid site id provided, assume that we have just openid
		# url instead of user name
		return $user;
	}
	my $site=$self->{$site_id};
	if (!index($site->{-format}[0],"%s")>0) {
		return $site->{-format}[0];
	}
	if ($site->{-translate_underscore}) {
		if (defined $site->{-format}[1] && ($user=~/^_/ || $user=~/_$/))
		{
			return sprintf $site->{-format}[1],$user);
		} else {
			$user =~ tr/_/-/;
		}
	}	
	return sprintf $site->{-format}[0],$user);
}

sub meaningless_url {
	my ($self,$id) = @_;
	return !$self->{$id}{-uri_as_name};
}

1;
