<?php

require_once __DIR__ . '/../../src/Events/Event.php';
require_once __DIR__ . '/../../src/Classes/Kobold.php';
require_once __DIR__ . '/../../src/Utilities/GameHelper.php';

class HuntingEvent extends Event
{
    public function getMinAge()
    {
        return 17;
    }

    public function getMinParticipants()
    {
        return 2;
    }

    public function getMaxParticipants()
    {
        return 5;
    }

    public function getCost()
    {
        return 25;
    }

    public function isAvailable()
    {
        return true;
    }

    private function runHunt(array $hunters, string $quarry, int $fullMin, int $fullMax, int $partialMin, int $partialMax)
    {
        $totalFood = 0;
        $successes = 0;

        $injuries = ['smallCut', 'brokenLeg', 'limp'];

        foreach ($hunters as $hunter) {
            $tracked = $hunter->checkStat('intelligence');
            $downed = $hunter->checkStat('fighting');

            if ($tracked && $downed) {
                $totalFood += rand($fullMin, $fullMax);
                $successes++;
            } elseif ($tracked || $downed) {
                $totalFood += rand($partialMin, $partialMax);
            }

            if (!$hunter->checkStat('vitality') && rand(1, 100) <= 15) {
                $injury = $injuries[array_rand($injuries)];
                if ($hunter->addInjury($injury))
                    $this->story .= "{$hunter->getName()} was hurt while chasing {$quarry}, but managed to limp back.\n";
            }
        }

        if ($successes === 0) {
            $this->story .= "The party failed to bring down any {$quarry}.\n";
        } else {
            $this->story .= "The party brought down {$quarry} and returned with food.\n";
        }

        return $totalFood;
    }

    private function spring(array $hunters, Kobold $bestTracker, Kobold $bestFighter, Kobold $toughest)
    {
        $this->story .= "Spring game was plentiful—rabbits and ground birds darted through the brush.\n";

        $totalFood = $this->runHunt($hunters, 'small game', 5, 8, 1, 2);

        if ($bestTracker->checkStat('intelligence') && rand(1, 100) <= 35) {
            $herbs = GameHelper::loadItem('healing-herbs');
            if ($herbs) {
                $this->tribe->addToStorage($herbs, rand(1, 2));
                $this->story .= "{$bestTracker->getName()} tracked fresh growth and gathered healing herbs along the way.\n";
            }
        }

        if (!$toughest->checkStat('vitality') && rand(1, 100) <= 25) {
            if ($toughest->addInjury('smallCut'))
                $this->story .= "A thicket tore at {$toughest->getName()}'s arms, leaving a nasty cut.\n";
        }

        return $totalFood;
    }

    private function summer(array $hunters, Kobold $bestTracker, Kobold $bestFighter, Kobold $toughest)
    {
        $this->story .= "Summer trails led to boar and wild goats, but the heat was punishing.\n";

        $totalFood = $this->runHunt($hunters, 'boar and goats', 6, 12, 1, 3);

        if ($bestFighter->checkStat('fighting') && rand(1, 100) <= 30) {
            $bonus = rand(3, 6);
            $totalFood += $bonus;
            $this->story .= "{$bestFighter->getName()} brought down a stubborn boar, adding extra meat.\n";
        }

        if (!$toughest->checkStat('vitality') && rand(1, 100) <= 25) {
            if ($toughest->addInjury('brokenLeg')) {
                $this->story .= "A charging beast knocked {$toughest->getName()} down, breaking a leg.\n";
            }
        }

        return $totalFood;
    }

    private function autumn(array $hunters, Kobold $bestTracker, Kobold $bestFighter, Kobold $toughest)
    {
        $this->story .= "Autumn brought fattened deer and migrating herds to track.\n";

        $totalFood = $this->runHunt($hunters, 'deer', 5, 9, 2, 4);

        if ($bestTracker->checkStat('intelligence') && rand(1, 100) <= 35) {
            $bonus = rand(3, 8);
            $totalFood += $bonus;
            $this->story .= "{$bestTracker->getName()} followed fresh tracks to a second herd.\n";
        }

        if (!$toughest->checkStat('vitality') && rand(1, 100) <= 20) {
            if ($toughest->addInjury('limp'))
                $this->story .= "A hidden root tripped {$toughest->getName()}, leaving {$toughest->him()} limping.\n";
        }

        return $totalFood;
    }

    private function winter(array $hunters, Kobold $bestTracker, Kobold $bestFighter, Kobold $toughest)
    {
        $this->story .= "Winter was harsh, and only lean game moved across the snow.\n";

        $totalFood = $this->runHunt($hunters, 'winter game', 2, 6, 0, 1);

        if ($bestFighter->checkStat('fighting') && rand(1, 100) <= 25) {
            $bonus = rand(2, 4);
            $totalFood += $bonus;
            $this->story .= "{$bestFighter->getName()} felled a tough quarry in the cold, adding a little extra meat.\n";
        }

        if (!$toughest->checkStat('vitality') && rand(1, 100) <= 30) {
            if ($toughest->addInjury('smallCut'))
                $this->story .= "Freezing winds numbed {$toughest->getName()}'s hands, and a slip left a painful cut.\n";
        }

        return $totalFood;
    }

    public function execute()
    {
        $this->story = "The hunting party set out into the wilderness...\n\n";

        $participantIds = $this->getParticipants();
        $hunters = [];
        foreach ($participantIds as $pid) {
            $k = $this->tribe->getKobold($pid);
            if ($k && !$k->isDead())
                $hunters[] = $k;
        }

        if (empty($hunters)) {
            $this->story .= "But there were no kobolds fit to hunt!";
            return $this->story;
        }

        if (count($hunters) > 1) {
            $this->story .= "A group of " . count($hunters) . " hunters set out:\n";
            foreach ($hunters as $hunter) {
                $this->story .= "- " . $hunter->getName() . "\n";
            }
            $this->story .= "\n";
        } else {
            $this->story .= $hunters[0]->getName() . " set out alone.\n\n";
        }

        $bestTracker = GameHelper::findBestKoboldForStat($hunters, 'intelligence');
        $bestFighter = GameHelper::findBestKoboldForStat($hunters, 'fighting');
        $toughest = GameHelper::findBestKoboldForStat($hunters, 'vitality');

        $this->story .= "{$bestTracker->getName()} tracked the trail while {$bestFighter->getName()} led the strike.\n";

        $season = $this->tribe->getCurrentSeason();
        $totalFood = 0;

        if ($season === 'spring') {
            $totalFood = $this->spring($hunters, $bestTracker, $bestFighter, $toughest);
        } elseif ($season === 'summer') {
            $totalFood = $this->summer($hunters, $bestTracker, $bestFighter, $toughest);
        } elseif ($season === 'autumn') {
            $totalFood = $this->autumn($hunters, $bestTracker, $bestFighter, $toughest);
        } else {
            $totalFood = $this->winter($hunters, $bestTracker, $bestFighter, $toughest);
        }

        if ($totalFood > 0) {
            $months = $this->tribe->foodMonthsLeft($totalFood);
            $this->tribe->addFood($totalFood);

            if ($months > 0) {
                if ($months == 1)
                    $this->story .= "The tribe gained a month worth of food from the hunt.\n";
                else
                    $this->story .= "The tribe gained {$months} months worth of food from the hunt.\n";
            } else
                $this->story .= "The hunt brought back {$this->tribe->foodTimeStr($totalFood)} worth of food.\n";
        } else {
            $this->story .= "The hunt brought back no usable food.\n";
        }

        if (rand(1, 100) <= 20) {
            $lucky = $hunters[array_rand($hunters)];
            if ($lucky->checkStat('intelligence')) {
                $splint = GameHelper::loadItem('bone-setting');
                if ($splint) {
                    $this->tribe->addToStorage($splint);
                    $this->story .= "{$lucky->getName()} found a sturdy bone and crafted a splint for the tribe.\n";
                }
            }
        }

        if (rand(1, 100) <= 20) {
            $unlucky = $hunters[array_rand($hunters)];
            if (!$unlucky->checkStat('vitality')) {
                $injuries = ['smallCut', 'brokenLeg', 'limp'];
                $injury = $injuries[array_rand($injuries)];
                if ($unlucky->addInjury($injury)) {
                    $this->story .= "Bad luck struck and {$unlucky->getName()} was injured on the way back.\n";
                }
            }
        }

        $this->story .= "\nThe hunters returned to the tribe.";

        return $this->story;
    }
}
