<?php

namespace Internetgalerie\IgDatapoolFe\Domain\Repository;

use TYPO3\CMS\Extbase\Persistence\Repository;
use TYPO3\CMS\Core\Country\CountryProvider;
use Internetgalerie\IgDatapoolFe\Domain\Model\Country;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;

#class CountryRepository extends \SJBR\StaticInfoTables\Domain\Repository\CountryRepository
class CountryRepository extends Repository
{
    protected $tablename = 'static_countries';
    protected $objectType = Country::class;
    protected $iso2Attribute = 'cn_iso_2';
    protected $iso3Attribute = 'cn_iso_3';

    public function findOneByCnIso_2(string $meCountryAbrev)
    {
        if (class_exists(CountryProvider::class)) {
            $countryProvider = GeneralUtility::makeInstance(CountryProvider::class);
            $systemCountry = $countryProvider->getByAlpha2IsoCode($meCountryAbrev);
            $systemCountryArray = array_values((array)$systemCountry);
            $country = new Country(...$systemCountryArray);
            return $country;
        } elseif (method_exists($this, 'findOneBy')) {
            return $this->findOneBy(['CnIso_2' => $meCountryAbrev]);
        } else {
            return parent::findOneByCnIso_2($meCountryAbrev);
        }
    }

    public function getIsoCountryName(string $languageTwoLetterIsoCode = '')
    {
        if (class_exists(CountryProvider::class)) {
            $countryProvider = GeneralUtility::makeInstance(CountryProvider::class);
            $systemCountries = $countryProvider->getAll();
            $countries = [];
            foreach($systemCountries as $systemCountry) {
                $systemCountryArray = array_values((array)$systemCountry);
                $countries[] = new Country(...$systemCountryArray);
            }
            return $countries;
        }
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($this->tablename);

        //$queryBuilder->quoteIdentifier($languageTwoLetterIsoCode);
        $countryNameAttributes = [];
        if (!$languageTwoLetterIsoCode) {
            $siteLanguage = $GLOBALS['TYPO3_REQUEST']->getAttribute('language');
            $languageTwoLetterIsoCode = $siteLanguage->getTwoLetterIsoCode();
        }

        if (isset($GLOBALS['TCA'][$this->tablename]['columns']['cn_short_' . $languageTwoLetterIsoCode])) {
            $countryNameAttributes[] = 'cn_short_' . $languageTwoLetterIsoCode;
        }
        $countryNameAttributes[] = 'cn_short_en';
        $countryNameAttributes[] = 'cn_official_name_local';

        $result = $queryBuilder
                ->selectLiteral('uid,' . $this->iso2Attribute . ' AS iso2,' . $this->iso3Attribute . ' AS iso3, COALESCE(' . implode(',', $countryNameAttributes) . ') AS name')
                ->from($this->tablename)->orderBy('name')->executeQuery();
        $rows = [];
        while ($row = $result->fetch()) {
            $row['localizedName'] = $row['name'];
            $rows[] = $row;
        }
        return $rows;
    }
}
