package Terse::View::Static;

use base 'Terse::View';

sub build_view {
	my ($self) = @_;
	$self->static_directory ||= 'root/static';
	$self->allowed = 'js|css|png|svg|jpeg|gif|json|html|txt';
	$self->mime = {
		js => 'application/javascript',
		css => 'text/css',
		png => 'image/png',
		svg => 'image/svg',
		jpeg => 'image/jpeg',
		gif => 'image/gif',
		json => 'application/json',
		html => 'text/html',
		txt => 'text/plain'
	};
	my $path = $0;
	$path =~ s/[^\/]+$//g;
	$self->dir = $path . $self->static_directory;
	#$self->memory_cached_templates = $self->_read_directory_content($self->dir) ;
	return $self;
}

sub render {
        my ($self, $t, $data) = @_;
	my $template = $t->captured->[0] || $data->template || $t->template || $t->req;
	$template = 'html/' . $template . '.html' if ($template !~ m/\.[^\.]+$/);
	my $allowed = $self->allowed;
	my ($mime) = $template =~ m/($allowed)$/;
	return $t->logError('Invalid file mime type for file: ' . $template, 500, 1) unless $mime && $self->mime->$mime;
	if ($self->memory_cached_resources) {
		return $t->logError('File not found: ' . $template, 500, 1) unless $self->memory_cached_resourcess->{$template};
		return ($self->mime->$mime, $self->memory_cached_resources->{$template});
	} else {
		my $file = $self->_read_file($self->dir . '/' . $template);
		$t->logError('File not found: ' . $template, 500, 1) && return unless $file;
		return ($self->mime->$mime, $file);
	}
}

sub _read_directory_content {
	my ($self, $dir) = @_;
	my $allowed = $self->allowed;
	return { map {
		( $_ => $self->_read_file("$dir/$_") );
	} $self->_recurse_directory("${dir}") };
}

sub _read_file {
	my ($self, $file) = @_;
	return unless -f $file;
	open my $fh, '<', $file or die "Cannot read html file: $file:" . $@;
	my $data = do { local $/; <$fh> };
	close $fh;
	return $data;
}

sub _recurse_directory {
        my ($self, $dir, $path, @files) = @_;
	return () unless -d $dir;
        opendir my $d, $dir or $self->logError("Cannot read controller directory: $!", 500, 1);
	my $allowed = $self->allowed;
        for (readdir $d) {
                next if $_ =~ m/^\./;
                if (-d "$dir/$_") {
                        $path .= "/$_" if $path;
                        push @files, $self->_recurse_directory("$dir/$_", $path || $_);
                } elsif ($_ =~ m/\.($allowed)$/) {
			#my $type_from_file = $self->ft->checktype_filename("$dir/$_");
			push @files, $path ? "$path/$_" : $_;
                }
        }
        closedir $d;
        return @files;
}

1;

=head1 NAME

Terse::View::Static - Serve static resources view

=cut

=head1 VERSION

Version 0.02

=cut

=head1 SYNOPSIS

	package MyApp::View::Static;

	use base 'Terse::View::Static';

	1;

=cut

=head1 LICENSE AND COPYRIGHT

L<Terse::Static>.

=cut
