<?php


namespace App\Model\Services;


use App\Model\Entities\Game;
use App\Model\Entities\GameData\Mmorpg\Faction;
use App\Model\Entities\GameData\Mmorpg\Region;
use App\Model\Entities\GameData\Mmorpg\Server;
use App\Model\Entities\MmorpgGuild;
use App\Model\Entities\PortalSite;
use App\Model\Entities\Security\User;
use Kdyby\Doctrine\Dql\Join;
use Kdyby\Doctrine\EntityRepository;
use Kdyby\Doctrine\QueryBuilder;

class SiteService extends BaseService
{
    /** @var EntityRepository */
    protected $sites;

    protected function startup()
    {
        parent::startup();

        $this->sites = $this->getRepository(PortalSite::class);
    }

    /**
     * @param int $id
     * @return null|PortalSite
     */
    public function findSiteById(int $id)
    {
        return $this->sites->find($id);
    }

    /**
     * @return null|PortalSite
     */
    public function findPortalSite()
    {
        return $this->sites->findOneBy(['isGlobalSite' => true]);
    }

    /**
     * @param User $createdBy
     * @param string $name
     * @return PortalSite
     */
    public function createPortalSite(User $createdBy, string $name) : PortalSite
    {
        $site = new PortalSite($createdBy);
        $site->setName($name);
        $site->setIsGlobalSite(true);

        $this->persist($site);
        return $site;
    }

    public function createGuild(User $createdBy, string $name, Game $game, Server $server, Faction $faction) : MmorpgGuild
    {
        $guild = new MmorpgGuild($createdBy);
        $guild->setName($name);
        $guild->setGame($game);
        $guild->setServer($server);
        $guild->setFaction($faction);

        $this->persist($guild);
        return $guild;
    }

    public function getGuildsGridDataSource($game) : QueryBuilder
    {
        return $this->getRepository(MmorpgGuild::class)->createQueryBuilder('g')
            ->whereCriteria(['game' => $game])
            ->leftJoin(Server::class, 's', Join::WITH, "s.id = g.server")
            ->leftJoin(Faction::class, 'f', Join::WITH, "f.id = g.faction")
            ->leftJoin(Region::class, 'r', Join::WITH, "r.id = s.region");
    }
}