# Chariot Extension for Wiki Pages
# ================================
#
# This extension enables the parsing of wiki pages with a section detailing the
# current state of chariot links.

package ATITD::Wiki::Page;

use strict;
use warnings;

# Load all chariot links from a this page.
sub load_chariot_links {
	my ($self, $heading) = @_;
	my $html = $self->tree;
	my $telling = $self->wiki->telling;
	
	# Search the correct section
	my $routes = $html->look_down(_tag => 'h2', sub {
		$_[0]->as_text eq $heading
	});

	die 'Did not find heading: '.$heading
		unless defined $routes;

	for my $region ($telling->regions) {
		# Search a sub-section for every region
		my $label = $routes->right;

		$label = $label->right
			while (defined $label && lc $label->as_text ne lc $region->name);
	
		next unless defined $label;
	
		# There needs to follow a table
		my $table = $label->right;
	
		next unless defined $table;
		next unless $table->tag eq 'table';
	
		# Find the rows; they need to be region: status format
		my @rows = $table->content_list;
	
		# Get rid of the headings
		shift @rows;
	
		for my $row (@rows) {
			my ($route_cell, $status_cell) = $row->content_list;
			my $route = $route_cell->as_text;
			my $status = $status_cell->as_text;
			
			# Remove bad whitespace/non-digits
			$route =~ s/^\s+//g;
			$route =~ s/\s+$//g;
			$status =~ s/\D//g;
			$status = 0 if $status eq '';
		
			# Establish that link
			my $link = $region->chariot->link($route);
			
			$link->set_needed($status) if defined $link;
		}
	}
}

1;
