<?php
namespace Medienreaktor\Products\Domain\Repository;

/***
 *
 * This file is part of the "Products" Extension for TYPO3 CMS.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 *  (c) 2017 Daniel Kestler &lt;daniel.kestler@medienreaktor&gt;, medienreaktor GmbH
 *
 ***/

/**
 * The repository for locations
 */
class LocationRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
    protected $defaultOrderings = [
        'is_top' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING,
        'name' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
    ];

    public function findAll() {
        $query = $this->createQuery();
        $query->getQuerySettings()->setRespectStoragePage(FALSE);
        return $query->execute();
    }

    public function findAllCountries() {
        $locations = $this->findAll();

        $countries = [];
        foreach ($locations as $location) {
            $country = $location->getCountry();

            if ($country && $country != '') {
                $sortableCountry = str_replace('Ö', 'Oe', $country);
                $sortableCountry = str_replace('Ä', 'Ae', $sortableCountry);
                $sortableCountry = str_replace('Ü', 'Ue', $sortableCountry);
                $countries[$sortableCountry]['country'] = $country;
                $countries[$sortableCountry]['locations'][] = $location;
            }
        }

        ksort($countries, SORT_NATURAL);

        return $countries;
    }

    public function findByCountry($country) {
        $query = $this->createQuery();
        $query->getQuerySettings()->setRespectStoragePage(FALSE);
        $query->matching($query->equals('country', $country));
        return $query->execute();
    }
}
