<?php

namespace KupShop\I18nBundle\Admin\lists;

use KupShop\I18nBundle\Translations\EmailsTranslation;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Mail\Email;
use Query\Operator;

class TranslateEmailsList extends TranslateList
{
    protected $template = 'list/translateEmails.tpl';

    protected $listType = 'translateEmails';

    public function __construct()
    {
        parent::__construct();
        $this->translation = ServiceContainer::getService(EmailsTranslation::class);
    }

    public function get_vars()
    {
        $vars = parent::get_vars();

        $email = ServiceContainer::getService(Email::class);

        $emailType = $email->getDefaultTypes();

        $newSQL = [];
        foreach ($vars['SQL'] as $object) {
            if (in_array($object['type'], $emailType)) {
                $emailService = $email->getServiceByType($object['type']);
                $object['name'] = $emailService::getName().($object['name'] ? ' - '.$object['name'] : '');
                $newSQL[] = $object;
            }
        }

        $vars['SQL'] = $newSQL;

        return $vars;
    }

    public function getQuery()
    {
        $query = parent::getQuery();

        $emailUtil = ServiceContainer::getService(Email::class);
        $order = join(',', array_map(function ($value) {
            return '"'.$value.'"';
        }, $emailUtil->getDefaultTypes()));

        $query['qb']->andWhere(Operator::inStringArray($emailUtil->getDefaultTypes(), 'e.type'))
            ->orderBy("FIELD(e.type, {$order}, \"ORDER_MESSAGE\")")
            ->addOrderBy('name');

        return $query;
    }
}

$main_class = TranslateEmailsList::class;
