#! /usr/bin/perl -T
use strict;
use warnings;
use HTML::Entities;
use utf8;

use lib '../include';
use itkaclcommon;

itkaclcommon::print_header();
my $entry = $itkaclcommon::cgi->param('entry');
itkaclcommon::print_tree(0, $entry);

my $ref = $itkaclcommon::dbh->selectrow_hashref('SELECT * FROM objects WHERE id=?', undef, $entry);

print "<script src=\"jquery-1.7.min.js\" type=\"text/javascript\"></script>\n";
print "<script src=\"itkacl.js\" type=\"text/javascript\"></script>\n";
print "<h1>$ref->{'description'}</h1>\n";

# Follow the tree up to the root to find the full path
my $path = "/" . $ref->{'name'};
my @ids = ();
while (defined($ref->{'parent'})) {
	$ref = $itkaclcommon::dbh->selectrow_hashref('SELECT * FROM objects WHERE id=?', undef, $ref->{'parent'});
	$path = "/" . $ref->{'name'} . $path;
	push @ids, $ref->{'id'};
}
	
print "<h2>$path</h2>\n";

#
# Now, fetch all ACL entries to find inherited rights; since ACLs are
# applied starting from the root, we traverse the tree from the root as
# well.
#

my $num_inherited = 0;
my $curpath = "";
for my $id (reverse @ids) {
	$ref = $itkaclcommon::dbh->selectrow_hashref('SELECT * FROM objects WHERE id=?', undef, $id);
	$curpath .= "/" . $ref->{'name'};
	
	my $aes = $itkaclcommon::dbh->selectall_arrayref('SELECT entity_type,entity,allow FROM aclentries WHERE object=? ORDER BY entity_type ASC, allow DESC',
		undef, $id);

	for my $ae (@{$aes}) {
		if ($num_inherited == 0) {
			# This is the first entry, we'll have to make
			# the table borders and such
			print <<"EOF";
<h3>Arvede rettigheter</h3>

<table>
  <tr>
    <th>#</th>
    <th>Till.</th>
    <th>Type</th>
    <th>Hvem</th>
    <th>Arvet fra</th>
  </tr>
EOF
		}
	
		my ($entity_type, $entity, $allow) = @{$ae};
		my $et_text;
		if ($entity_type eq 'group') {
			$et_text = 'Gruppe';
		} else {
			$et_text = 'Bruker';
		}
		my $e_text = HTML::Entities::encode_entities($entity);
	
		++$num_inherited;
		print <<"EOF";
  <tr>
    <td>$num_inherited</td>
    <td style="text-align: center;"><img src="/img/$allow.png" alt="$ae->[2]" /></td>
    <td>$et_text</td>
    <td>$e_text</td>
    <td><a href="/view.pl?entry=$id">$curpath</a></td>
  </tr>
EOF
	}
}

if ($num_inherited != 0) {
	print "</table>\n";
}

#
# Same, for non-inherited rights. Yes, it's a bit of code duplication,
# but it really won't be that much cleaner implementing it as a
# function, unfortunately.
#

print "<h3>Rettigheter</h3>\n";

my $num_rights = 0;
$ref = $itkaclcommon::dbh->selectrow_hashref('SELECT * FROM objects WHERE id=?', undef, $entry);
my $aes = $itkaclcommon::dbh->selectall_arrayref('SELECT entity_type,entity,allow,comment FROM aclentries WHERE object=? ORDER BY entity_type ASC, allow DESC',
	undef, $entry);

for my $ae (@{$aes}) {
	if ($num_rights == 0) {
		# This is the first entry, we'll have to make
		# the table borders and such
		print <<"EOF";

<table>
  <tr>
    <th>#</th>
    <th>Till.</th>
    <th>Type</th>
    <th>Hvem</th>
    <th>Slett</th>
    <th>Kommentar</th>
  </tr>
EOF
		}
	
	my ($entity_type, $entity, $allow, $comment) = @{$ae};
	my $et_text;
	if ($entity_type eq 'group') {
		$et_text = 'Gruppe';
	} else {
		$et_text = 'Bruker';
	}
	my $e_text = HTML::Entities::encode_entities($entity);
	my $c_text = HTML::Entities::encode_entities($comment // '');

	++$num_rights;
	print <<"EOF";
  <tr>
    <td>$num_rights</td>
    <td style="text-align: center;"><img src="/img/$allow.png" alt="$ae->[2]" /></td>
    <td>$et_text</td>
    <td>$e_text</td>
    <td style="text-align: center;">
      <a href="/delete.pl?entry=$entry&amp;entity_type=$entity_type&amp;entity=$e_text&amp;csrftoken=$itkaclcommon::masked_csrf_token">
        <img src="/img/delete.png" alt="Slett" />
      </a>
    </td>
    <td ondblclick="enableEdit(this);" itkacl:entry="$entry" itkacl:entity-type="$entity_type" itkacl:entity="$e_text" itkacl:csrftoken="$itkaclcommon::masked_csrf_token">$c_text</td>
  </tr>
EOF
}

if ($num_rights != 0) {
	print "</table>\n";
} else {
	print "<p>Ingen rettigheter er satt ennå for dette objektet.</p>\n";
}

#
# I'm a bit unsure if we want to have this all in one page, but OK, here
# goes...
#
print <<"EOF";

<h3>Legg til nye rettigheter</h3>

<p>Du kan legge til nye rettigheter på dette objektet. Merk at verdiene
  dine ikke vil sjekkes for gyldighet (du kan mao. fint gi tilganger til
  en ikke-eksisterende bruker eller gruppe, men det kan gi uforutsigbare
  resultater ved ACL-sjekking seinere).</p>

<p>Den spesielle gruppen "&lt;everyone&gt;" inneholder alle brukere.</p>

<form method="post" action="add.pl">
  <input type="hidden" name="csrftoken" value="$itkaclcommon::masked_csrf_token" />
  <input type="hidden" name="entry" value="$entry" />
  <table>
    <tr style="text-align: left;">
      <th>Tillatelse:</th>
      <td>
        <select name="allow">
	  <option value="deny">Nekt</option>
	  <option value="grant">Tillat</option>
	</select>
      </td>
    </tr>
    <tr style="text-align: left;">
      <th>Type:</th>
      <td>
        <select name="entity_type">
	  <option value="user">Bruker</option>
	  <option value="group">Gruppe</option>
	</select>
      </td>
    </tr>
    <tr style="text-align: left;">
      <th>Bruker-/gruppenavn:</th>
      <td><input name="entity" size="16" /></td>
    </tr>
    <tr style="text-align: left;">
      <th>Kommentar:</th>
      <td><input name="comment" size="40" /></td>
    </tr>
    <tr>
      <td colspan="2" style="text-align: center;">
        <input type="submit" value="Legg til" />
      </td>
    </tr>
  </table>
</form>

<h3>Legg til nye tilgangsområder</h3>

<p>Du kan legge til nye tilgangsområder under denne noden. Merk at du
  er begrenset til store og små bokstaver (kun små anbefales, områder
  er case-sensitive) samt tall og bindestrek.</p>

<form method="post" action="addnode.pl">
  <input type="hidden" name="csrftoken" value="$itkaclcommon::masked_csrf_token" />
  <input type="hidden" name="parent" value="$entry" />
  <table>
    <tr style="text-align: left;">
      <th>Sti:</th>
      <td>
        $path/<input name="name" size="16" />
      </td>
    </tr>
    <tr style="text-align: left;">
      <th>Beskrivelse</th>
      <td>
        <input name="description" size="50" />
      </td>
    </tr>
    <tr>
      <td colspan="2" style="text-align: center;">
        <input type="submit" value="Legg til" />
      </td>
    </tr>
  </table>
</form>

<h3>Slett dette området</h3>

EOF

$ref = $itkaclcommon::dbh->selectrow_hashref('SELECT COUNT(*) AS num_aclentries FROM aclentries WHERE object=?', undef, $entry);
if ($ref->{'num_aclentries'} > 0) {
	print <<"EOF";
<p>Du kan ikke slette dette området ettersom det har tilordnet tilganger. Dersom du ønsker å
  slette det må du først slette alle tilganger og eventuelle underområder.</p>
EOF
} else {
	$ref = $itkaclcommon::dbh->selectrow_hashref('SELECT COUNT(*) AS num_children FROM objects WHERE parent=?', undef, $entry);
	if ($ref->{'num_children'} > 0) {
		print <<"EOF";
<p>Du kan ikke slette dette området ettersom det har underområder. Dersom du ønsker å slette
  det må du først slette alle underområdene.</p>
EOF
	} else {
		print <<"EOF";
<p>Dersom du ønsker, kan du slette dette området. All tilgangskontroll mot det i fremtiden vil
  feile, så sjekk grundig før du sletter det at det ikke fortsatt er i bruk.</p>
  
<form method="post" action="deletenode.pl">
  <input type="hidden" name="csrftoken" value="$itkaclcommon::masked_csrf_token" />
  <input type="hidden" name="entry" value="$entry" />
  <p><input type="submit" value="Slett dette området" /></p>
</form>
EOF
	}
}

itkaclcommon::print_footer();
