<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele De Nobili
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\AdminBar\Filler;

use Application\Admin\AdminBar\AdminBar;
use Application\Admin\AdminBar\FillerInterface;
use Application\Core\Entity\SiteInterface;
use Application\Core\I18n\Translation\Translator;
use Application\Core\User;
use Pongho\Menu\Item;

class UserFiller implements FillerInterface
{
    /**
     * @var SiteInterface
     */
    protected $site;

    /**
     * @var User
     */
    protected $user;

    /**
     * @var Translator
     */
    protected $translator;

    public function __construct(SiteInterface $site, User $user, Translator $translator)
    {
        $this->site = $site;
        $this->user = $user;
        $this->translator = $translator;
    }

    /**
     * {@inheritdoc}
     */
    public function fill(AdminBar $admin_bar)
    {
        // Utente
        $admin_bar->right->add($this->getUserSettingsItem());

        // Logout
        $admin_bar->right->add($this->getLogoutItem());
    }

    /**
     * @return Item
     */
    protected function getUserSettingsItem()
    {
        $item = new Item(
            $this->getUserSettingsItemLabel(),
            $this->getUserSettingItemUrl(),
            ['title' => '']
        );

        $item->addClass('pongho-admin-bar-user-settings');

        return $item;
    }

    /**
     * @return string
     */
    protected function getUserSettingsItemLabel()
    {
        $account = $this->user->getAccount();

        $avatar_url = src(
            $account->getAvatar(),
            'adminbaravatar',
            '//www.gravatar.com/avatar/' . md5($account->getEmail()) . '?s=20&amp;d=mm'
        );

        return $account->getUsername() . ' <img src="' . $avatar_url . '" alt="' . $account->getUsername() . '">';
    }

    /**
     * @return string
     */
    protected function getUserSettingItemUrl()
    {
        return pongho_url('/users/edit/' . $this->user->getAccount()->getId() . '/?site=' . $this->site->getId());
    }

    /**
     * @return Item
     */
    protected function getLogoutItem()
    {
        return new Item($this->getLogoutItemLabel(), $this->getLogoutItemUrl());
    }

    /**
     * @return string
     */
    protected function getLogoutItemLabel()
    {
        return $this->translator->trans('Logout');
    }

    /**
     * @return string
     */
    protected function getLogoutItemUrl()
    {
        return url('/user/logout/');
    }
}
