<?php

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

class FarmingEvent extends Event
{
    public function getMinAge()
    {
        return 10;
    }

    public function getMinParticipants()
    {
        return 2;
    }

    public function getMaxParticipants()
    {
        return 6;
    }

    public function getCost()
    {
        switch ($this->tribe->getCurrentSeason()) {
            case 'spring':
                return 25;
            case 'summer':
                return 15;
            case 'autumn':
                return 20;
            case 'winter':
                return 60;
            default:
                return 60;
        }
    }

    public function isAvailable()
    {
        if ($this->tribe->getCurrentSeason() !== 'winter') {
            if ($this->tribe->getCurrentSeason() === 'spring')
                return !isset($this->tribe->dataStore->wasSowedInSpring) || !$this->tribe->dataStore->wasSowedInSpring;

            if ($this->tribe->getCurrentSeason() === 'summer')
                return isset($this->tribe->dataStore->wasSowedInSpring) && $this->tribe->dataStore->wasSowedInSpring;

            if ($this->tribe->getCurrentSeason() === 'autumn')
                return isset($this->tribe->dataStore->wasTendedInSummer) && $this->tribe->dataStore->wasTendedInSummer;
        }

        // reset values since this part of the code is only ever reached in winter so we might as well.
        $this->tribe->dataStore->wasSowedInSpring = false;
        $this->tribe->dataStore->wasTendedInSummer = false;
        return false;
    }

    public function spring(array $all, Kobold $bestInt, Kobold $bestVit)
    {
        $successes = 0;
        $this->tribe->dataStore->farmYieldMultiplier = 0.5;
        $this->tribe->dataStore->wasSowedInSpring = true;

        for ($i = 0; $i < count($all); $i++) {
            $farmer = $all[$i];

            if ($farmer->checkStat('vitality') || $farmer->checkStat('intelligence')) {
                $this->tribe->dataStore->farmYieldMultiplier += 1;
                $successes++;
            }

            if (!$farmer->checkStat('will') && rand(1, 100) <= 30) {
                if ($farmer->addInjury("smallCut"))
                    $this->story .= "{$farmer->getName()} had an accident plowing the field, cutting {$farmer->his()} leg with the hoe.\n";
                break;
            }
        }

        $word = "terribly";
        $perc = ($successes / $this->getMaxParticipants());

        if ($perc >= 0.95)
            $word = "perfectly";
        else if ($perc >= 0.75)
            $word = "great";
        else if ($perc >= 0.5)
            $word = "well";
        else if ($perc >= 0.25)
            $word = "okay";
        else if ($perc >= 0.1)
            $word = "badly";

        $this->story .= "Tilling and sowing the fields went {$word}.\n";

        $this->tribe->dataStore->wasSowedInSpring = true;
    }

    public function summer(array $all, Kobold $bestInt, Kobold $bestVit)
    {
        $successes = 0;
        $this->tribe->dataStore->wasSowedInSpring = false;
        $this->tribe->dataStore->wasTendedInSummer = true;

        for ($i = 0; $i < count($all); $i++) {
            $farmer = $all[$i];

            if ($farmer->checkStat('vitality') || $farmer->checkStat('intelligence')) {
                $this->tribe->dataStore->farmYieldMultiplier += 0.5;
                $successes++;
            }

            if (!$farmer->checkStat('vitality') && rand(1, 100) <= 25) {
                if ($farmer->addInjury("sunburn"))
                    $this->story .= "{$farmer->getName()} got badly sunburned while working in the fields under the hot sun.\n";
                break;
            }

            if ($farmer->checkStat('intelligence') && rand(1, 100) <= 40) {
                $herbs = GameHelper::loadItem('healing-herbs');
                $this->tribe->addToStorage($herbs, rand(1, 3));
                $this->story .= "{$farmer->getName()} managed to grow some useful healing herbs while tending the crops.\n";
                break;
            }
        }

        $word = "terribly";
        $perc = ($successes / $this->getMaxParticipants());

        if ($perc >= 0.95)
            $word = "perfectly";
        else if ($perc >= 0.75)
            $word = "great";
        else if ($perc >= 0.5)
            $word = "well";
        else if ($perc >= 0.25)
            $word = "okay";
        else if ($perc >= 0.1)
            $word = "badly";

        $this->story .= "Tending to the crops went {$word}.\n";
    }

    public function autumn(array $all, Kobold $bestInt, Kobold $bestVit)
    {
        $harvestBaseMultiplier = 3.0;
        $this->tribe->dataStore->wasTendedInSummer = false;

        $multiplier = $this->tribe->dataStore->farmYieldMultiplier ?? 1.0;
        if (!$bestInt->checkStat('intelligence')) {
            $this->story .= "Unfortunately, {$bestInt->getName()} made several mistakes in {$bestInt->his()} plan to harvest the crops.\n";
            $this->story .= "Despite {$bestVit->getName()}'s best efforts, many crops were lost.\n";
            $multiplier *= floatval(rand(2, 6)) * 0.1;
        }

        $totalFood = 0;
        $mostFood = 0;
        $mostFarmedBy = '';

        for ($i = 0; $i < count($all); $i++) {
            $farmer = $all[$i];

            $farmed = rand(0, $this->tribe->foodRequirements[$farmer->getAgeCategory()] * $harvestBaseMultiplier) * $multiplier;
            $totalFood += $farmed;

            if ($farmed > $mostFood) {
                $mostFood = $farmed;
                $mostFarmedBy = $farmer->getName();
            }
        }

        if ($mostFarmedBy == $bestVit->getName()) {
            $this->story .= "{$bestVit->getName()} worked the hardest and managed to harvest the most food for the tribe!\n";
        } else {
            $this->story .= "Despite {$bestVit->getName()} working the hardest out of everyone, it was {$mostFarmedBy} who harvested the most food for the tribe.\n";
        }


        $reason = $this->tribe->modifyFoodGain($totalFood);
        if ($reason === 'draught') {
            $this->story .= "The drought wilted the crops, halving what could be gathered.\n";
        } elseif ($reason === 'heatWave') {
            $this->story .= "The heat wilted the crops, halving what could be gathered.\n";
        }
        $months = $this->tribe->foodMonthsLeft($totalFood);
        $this->tribe->addFood($totalFood);

        $max = $this->tribe->foodRequirements[GameHelper::getAgeCategory("adult")] * $harvestBaseMultiplier * $multiplier * $this->getMaxParticipants();

        $word = "terribly";
        $perc = ($totalFood / $max);

        if ($perc >= 0.95)
            $word = "perfectly";
        else if ($perc >= 0.75)
            $word = "great";
        else if ($perc >= 0.5)
            $word = "well";
        else if ($perc >= 0.25)
            $word = "okay";
        else if ($perc >= 0.1)
            $word = "badly";

        $this->story .= "Tending to the crops went {$word}.\n";

        if ($months < 1)
            $this->story .= "The tribe gained only {$this->tribe->foodTimeStr($totalFood)} worth of food from the harvest.\n";
        else {
            if ($months == 1)
                $this->story .= "The tribe gained only a month worth of food from the harvest.\n";
            else
                $this->story .= "The tribe gained " . $months . " months worth of food from the harvest!\n";
        }
    }

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

        $leader = GameHelper::findBestKoboldForStat($explorers, "intelligence");
        $hardestWorker = GameHelper::findBestKoboldForStat($explorers, "vitality");

        $this->story = "The farmers tended to the fields. {$leader->getName()} took the lead.\n";

        if ($this->tribe->getCurrentSeason() === 'spring')
            $this->spring($explorers, $leader, $hardestWorker);
        else if ($this->tribe->getCurrentSeason() === 'summer')
            $this->summer($explorers, $leader, $hardestWorker);
        else if ($this->tribe->getCurrentSeason() === 'autumn')
            $this->autumn($explorers, $leader, $hardestWorker);

        return $this->story;
    }
}
