#!/usr/bin/perl

# Copyright (C) 2007 王亮 <netcasper AT gmail DOT com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public Licence as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.

# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public Licence for more details.

use strict;
use warnings;

use XML::OPML;
use XML::Feed;
use Encode;

for my $opml_file (@ARGV) {
    my $opml = XML::OPML->new;
    $opml->parse($opml_file);
    print $opml->head->{title}, "\n";
    for my $outline (@{$opml->outline}) {
	if (exists $outline->{opmlvalue} and $outline->{opmlvalue} eq 'embed') {
	    my $title;
	    my @embedded_outlines;
	    for my $key (keys %$outline) {
		if (ref $outline->{$key} eq "HASH") {
		    push @embedded_outlines, $outline->{$key};
		}
		elsif ($key eq 'title') {
		    $title = $outline->{$key};
		}
		elsif ($key eq 'text') {
		    $title = $outline->{$key} unless defined $title;
		}
	    }
	    print "  $title\n";
	    print_outline($_, 2) for @embedded_outlines;
	}
	else {
	    print_outline($outline, 1);
	}
    }
}

sub print_outline {
    my $outline = shift;
    my $indent = shift;

    my $title;
    if (exists $outline->{title}) {
	$title = $outline->{title};
    } elsif (exists $outline->{text}) {
	$title = $outline->{text};
    } else {
	$title = "N/A";
    }
    print "  " x $indent, encode_utf8($title), "\n";
    if (exists $outline->{htmlUrl}
	and ! $outline->{htmlUrl} eq "") {
	my $htmlUrl = $outline->{htmlUrl};
	print "  " x ($indent + 1), $htmlUrl, "\n";
	my @feeds = XML::Feed->find_feeds($htmlUrl);
	my $xmlUrl = "\L$outline->{xmlUrl}\E";
	for my $feed (@feeds) {
	    print "  " x ($indent + 1), $feed, "\n"
		unless "\L$feed\E" eq $xmlUrl;
	}
    }
    print "  " x ($indent + 1), "[", $outline->{xmlUrl}, "]\n";
}
