<?php

namespace AuthStack\Driver\System;

use function Buckhill\config;
use AuthStack\Driver\User\AbstractUser;
use AuthStack\Driver\User\UserInterface;
use AuthStack\Driver\Model\User as SystemUser;

class User extends AbstractUser implements UserInterface
{
    protected $cfg_key;
    protected $attributes = [];


    public static function fromModel(SystemUser $model, $cfg)
    {
        $me = new static;

        // Fetch the config attribute (this is a JSON field in DB)
        $config = $model->getAttribute('config');

        // Check if the JSON contains 'attributes' key - these are custom attributes that we can fill out via config
        $values = isset($config['attributes']) ? $config['attributes'] : [];

        $attributes = [];

        // Attributes come in form of ['attr' => 'value'] and we need them as [attr] = 'value'
        if(sizeof($values))
        {
            foreach($values as $entry)
            {
                if(isset($entry['name']) && isset($entry['value']))
                {
                    $attributes[$entry['name']] = $entry['value'];
                }
            }
        }

        $attributes = collect(array_merge(['id' => $model->id, 'username' => $model->username], $attributes))
            ->all()
        ;

        $me->cfg_key = $cfg;
        $me->pkey_value = $model->id;
        $me->attributes = $attributes;

        $me->setAdmin();

        return $me;
    }


    /**
     * @param string $key
     * @param null   $default
     *
     * @return mixed
     */
    public function getAttribute($key = '', $default = null)
    {
        return isset($this->attributes[$key]) ? $this->attributes[$key] : $default;
    }


    /**
     * @return string
     */
    public function getFullName()
    {
        return sprintf("%s %s", $this->getAttribute('first_name', 'N/A'), $this->getAttribute('last_name', 'N/A'));
    }


    /**
     * @return array|float|int|string
     */
    public function getEmail()
    {
        return $this->getAttribute('email', 'N/A');
    }


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


    /**
     * @param      $attr
     * @param null $default
     *
     * @return mixed|null
     */
    protected function fromConfigAttribute($attr, $default = null)
    {
        $cfg = $this->getAttribute('config');

        if(!is_array($cfg)) return $default;

        return isset($cfg[$attr]) ? $cfg[$attr] : $default;
    }
}