<?php

namespace onespace\tools\widgets\ui;

use Exception;
use onespace\tools\widgets\ui\base\ImgBase;
use Yii;

/**
 * Returns the profile picture of a specified (or logged in) user, as a link if desired.
 * 
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

class ProfilePic extends ImgBase {

    /**
     * The full namespace and class name of the user model class.
     * Options:
     * - app\models\User
     * - common\models\User
     * 
     * @var string  $userClass  Default: 'common\models\User'
     * 
     * @access  public
     */

    public string $userClass = 'common\models\User';

    /**
     * Retrieve this specified user's profile picture. If not set, it retrieves the current logged in user's picture
     * 
     * @var int $userId
     * 
     * @access  public
     */

    public int $userId;

    /**
     * {@inheritdoc}
     * 
     * @throws  Exception   If no User model class is defined
     */

    public function init(): void {
        parent::init();
        $this->userId ??= Yii::$app->user->id;
        $this->options['class'] ??= '';
    }

    /**
     * {@inheritdoc}
     * 
     * @return string
     */

    public function run(): string {
        parent::run();

        $user = $this->userClass::findOne(['id' => $this->userId]);
        $link = Yii::$app->params['serviceUrls']['userUi'] . 'avatar/' . $user->dynamics_guid;

        return $this->createImgHtml($link);
    }
}
