#
# TV::Core - constants used across the TV pages
# ~~~~~~~~   (c) Andrew Flegg 2002. Released under the Artistic Licence.


package TV::Core;

use vars qw(@CHANNELS %GROUPS %NICENAME
            $DATA_DIR);

$DATA_DIR = '/home/jaffa/bleb/services/tv/data';
@CHANNELS = ();
%NICENAME = ();
%GROUPS   = (
    terrestrial => [qw(bbc1 bbc2 itv1 ch4 five)]
);



# -- Grab a list of all available channels ----------------------------
#
sub _getAllChannels {
    return \@CHANNELS if @CHANNELS;

    opendir(DIR, "$DATA_DIR/channels") or return;
    foreach my $f (sort(readdir(DIR))) {
        next unless $f =~ m!^.*?([^/]+)\.xml$!;
        push @CHANNELS, $1;
    }
    closedir(DIR);
    return \@CHANNELS;
}


# -- Get a list of channels -------------------------------------------
#
sub getChannels {
    my $class = shift;
    my $type  = shift || 'all';
    my $sort  = shift || 'terrestrial';

    return $GROUPS{$type} if $GROUPS{$type};

    my $data  = [];

    if ($type eq 'all') {
        if (($sort eq 'terrestrial')
          ||($sort eq 'telewest')
          ||($sort eq 'sky')
          ||($sort eq 'freeview')) {
            push @$data, @{ $class->getChannels($sort) };
            my %get   = map { $_ => 1 } @{ _getAllChannels() };
            my %there = map { $_ => 1 } @$data;
            foreach my $c (@CHANNELS) {
                push @$data, $c if $get{$c} and !$there{$c};
            }

        } elsif ($sort eq 'alphabetical') {
            $data = _getAllChannels();
        }

    } elsif (($type eq 'freeview')
           ||($type eq 'sky')
           ||($type eq 'telewest')) {
        open(IN, "<$DATA_DIR/groups/$type.dat") or return [];
        my %get = map { $_ => 1 } @{ _getAllChannels() };
        while(<IN>) { chomp; push @$data, $_ if $get{$_}; }
        close(IN);
        $GROUPS{$type} = $data;

    } else {
        $data = _getAllChannels();
    }
    return $data;
}


# -- Get a nice channel list ------------------------------------------
#
sub niceChannelName {
    my $class  = shift;
    my $orig   = shift;
    my $nice   = $orig;
    return $NICENAME{$orig} if $NICENAME{$orig};

    $nice =~ s/(\w{2,}?)(\d+)/$1 $2/g;
    $nice =~ s/_/ /g;
    $nice =~ s/bbc/BBC/g;
    $nice =~ s/itv/ITV/g;
    $nice =~ s/ch /Channel /g;
    $nice =~ s/uk /UK /g;
    $nice =~ s/ (.)/" ".ucfirst($1)/eg;
    $nice = ucfirst($nice);

    return $NICENAME{$orig} = $nice;
}




1;
    
