<?php

namespace Drupal\materio_user\Plugin\Block;

use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;

/**
 * Provides a 'UserBlock' block.
 *
 * @Block(
 *  id = "user_block",
 *  admin_label = @Translation("User block"),
 * )
 */
class UserBlock extends BlockBase   implements ContainerFactoryPluginInterface{

    protected $user;

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
      // Instantiates this form class.
      return new static(
        $configuration,
        $plugin_id,
        $plugin_definition,
        $container->get('current_user')
      );
    }

    /**
    * @param array $configuration
    * @param string $plugin_id
    * @param mixed $plugin_definition
    * @param \Drupal\Core\Session\AccountProxyInterface $account
    */
    public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account) {
      parent::__construct($configuration, $plugin_id, $plugin_definition);
      $this->user = $account;
    }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    // dpm($this->user);
    if($this->user->id()){
      $user_url = Url::fromRoute('entity.user.canonical', ['user' => $this->user->id()]);
      $build['user-link'] = array(
        '#title' => $this->user->getEmail(),
        '#type' => 'link',
        '#url' => $user_url,
        '#options'=>array(
          'attributes' => array(
            'data-drupal-link-system-path' => $user_url->getInternalPath(),
            'alt' => t('User account'),
          )
        )
      );
      $logout_url = Url::fromRoute('user.logout');
      $build['user-logout'] = array(
        '#title' => t('Logout'),
        '#type' => 'link',
        '#url' => $logout_url,
        '#options'=>array(
          'attributes' => array(
            'data-drupal-link-system-path' => $logout_url->getInternalPath(),
            'alt' => t('Logout'),
          )
        )
      );
    }
    return $build;
  }

}
