<?php

namespace AuthStack\Driver\AUDGeneric;

use Illuminate\Support\Collection;
use function Buckhill\config as cfg;
use AuthStack\Driver\User\AbstractUser;
use AuthStack\Driver\User\UserInterface;

class User extends AbstractUser implements UserInterface
{
    /**
     * @var
     */
    protected $collection;

    /**
     * @var
     */
    protected $cfg_key;

    /**
     * @var bool
     */
    protected $is_admin = false;

    /**
     * @param Collection $attributes
     * @param $cfg_key
     * @return static
     */
    public static function initialize(Collection $attributes, $cfg_key)
    {
        $me = new static();

        $me->collection = $attributes;
        $me->cfg_key = $cfg_key;

        return $me;
    }

    public function setPrimaryKeyValue($value)
    {
        $this->pkey_value = $value;
    }

    /**
     * @return bool
     */
    public function checkIfAdmin()
    {
        // Attribute to fetch from user collection
        $attribute = $this->config('administrative.attribute');

        // Value to check against
        $value = $this->config('administrative.value');

        // If empty (null, false, 0, '') then return false instantly
        if(empty($attribute) || empty($value))
        {
            return false;
        }

        $user_attribute = $this->getCollection()->get($attribute, null);

        // Compare hashes of two values
        return 0 === strcmp(sha1($value), sha1($user_attribute));
    }

    /**
     * @return bool
     */
    public function isAdmin()
    {
        return $this->is_admin;
    }

    /**
     * @return $this
     */
    public function setAdmin()
    {
        $this->is_admin = true;

        return $this;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return $this->getCollection()->toArray();
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->getCollection()->get('email_primary', 'N/A');
    }

    /**
     * @return string
     */
    public function getFullName()
    {
        $c = $this->getCollection();

        return sprintf("%s %s", $c->get('first_name', 'N/A'), $c->get('last_name', 'N/A'));
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->getCollection()->get('user_username');
    }

    /**
     * @param string $key
     * @param null $default
     * @return mixed
     */
    public function getAttribute($key = '', $default = null)
    {
        return $this->getCollection()->get($key, $default);
    }

    /**
     * @return Collection
     */
    protected function getCollection()
    {
        return $this->collection;
    }

    /**
     * @param      $key
     * @param null $default
     *
     * @return string|int|float|array|null
     */
    protected function config($key, $default = null)
    {
        return cfg(sprintf('%s.%s', $this->cfg_key, $key), $default);
    }
}
