#!/usr/bin/perl
# This needs to be stackless.
#use Fcntl q{:flock};
#use Mooix::Thing;
#use Mooix::Root;
	       
sub break_open {
	my $this=shift;

	# Lock both this side and the otherside to prevent races.
	require $this->fieldfile("getlock.pl");
	my @locks=getduallock($this, LOCK_EX, "closed");

	if ($this->closed) {
		$this->msg("break_open");
		if ($this->otherside) {
			$this->otherside->msg("break_open");
		}
		$this->unlock if $this->locked;
		$this->open(quiet => 1);
		return 0;
	}
}

run sub {
	my $this=shift;
	my $damage=shift;
	my $quiet=shift;

	return if $this->unbreakable;
	
	# Enough damage is noticed on the other side too.
	if (! $quiet && $damage >= 1 && $this->otherside) {
		$this->otherside->msg("otherside_damage");
	}
	
	# Sudden hard knocks can force a door open with no permenent
	# damage. This should really only work for hits on the right side
	# of a door, since most doors only open in one direction easily.
	# To get that effect, make the side that opens easily have less
	# hitpoints.
	if ($damage >= $this->hitpoints / 3 && $damage < $this->hitpoints &&
	    $this->closed) {
		break_open($this);
	}
	
	my $hitpoints = $this->hitpoints($this->hitpoints - $damage);

	if ($hitpoints <= 0) {
		if ($this->closed) {
			break_open($this);
		}
		else {
			$this->msg("break") unless $quiet;
		}

		my $name = $this->name;
		# Add name to aliases.
		my @aliases=$this->alias;
		if (! grep { $name eq $_ } @aliases) {
			$this->alias(@aliases, $name);
		}
		# Change name.
		$this->name("broken ".$this->name);
		# And add broken to its adjectives too.
		my @adjectives=$this->adjective;
		if (! grep { "broken" eq $_ } @adjectives) {
			$this->adjective(@adjectives, "broken");
		}
		
		# Reparent to concrete exit so it cannot be locked or
		# closed anymore.
		$this->parent($Mooix::Root->concrete->exit);

		# Knock the other side down to 0 hitpoints, so it will break
		# in the same way.
		if ($this->otherside) {
			$this->otherside->damage($this->otherside->hitpoints, 1);
		}
	}
}
