package WM::System;

use strict;
use warnings;

use base 'Mojolicious::Controller';

use Data::Dump qw/dump/;
use JSON;

my $remote = 'ssh mjesec';
#$remote = ''; # FIXME

sub exhibit {
    my ($self, $c) = @_;
	warn "## c = ",dump( $c );
	$c->render;
}

=for later

sub vzlist {
    my ($self, $c) = @_;

	$self->text_plain( $c->res, 'sudo /usr/sbin/vzlist' );

}


sub text_plain {
	my ( $self, $res, $command ) = @_;
	$res->code(200);
    $res->headers->content_type('text/plain');
	$res->body( scalar `COLUMNS=128 $remote $command` );
}


=cut

sub json {
	my ( $self, $res, $data ) = @_;
	$res->code(200);
    $res->headers->content_type('application/javascript');
	$res->body( to_json( $data ) );
}


sub df {
    my ($self, $c) = @_;

	my $df = `$remote df -kT`;
	my @lines = split(/\n/, $df);
	my @header = map { lc($_) } split(/\s+/, shift @lines, 7);

	my @items;
	my $number;

	while ( @lines ) {
		my $item;
		my @v = split(/\s+/, shift @lines);
		if ( $#v == 0 ) {
			my $cont = shift @lines;
			$cont =~ s/^\s+//;
			push @v, split(/\s+/, $cont);
		}
		foreach my $i ( 0 .. $#header ) {
			my $name = lc( $header[$i] );
			$name =~ s/[^a-z0-9]+/_/g;
			$name =~ s/^([0-9])/_$1/;
			$name =~ s/_+$//;
			my $val = $v[$i];
			$number->{$name}++ if $val =~ s/^(\d+)%?$/$1/;
			$item->{ $name } = $val;

			$item->{ label } = $val if $name =~ m/mounted/;
		}
		warn "left ",dump(@v) if @v;
		push @items, $item;
	}

	warn "# items = ",dump( @items );
	warn "# number [$#items] = ",dump( $number );

	$self->json( $c->res, {
		items => [ @items ],
		properties => {
			map { $_ => { valueType => 'number' } }
			grep { $number->{$_} == $#items + 1 }
			keys %$number
		}
	} );
}

1;
