<?php

namespace dokuwiki\plugin\bez\mdl;

class UserFactory {

	private $model;

	/** @var array|null Cache de usuarios a nivel de request */
	private $allUsersCache = null;

	public function __construct($model) {
		$this->model = $model;
	}

	public function get_all() {
		if ($this->allUsersCache !== null) {
			return $this->allUsersCache;
		}

		$wikiusers = $this->model->dw_auth->retrieveUsers();

		$a = array();
		foreach ($wikiusers as $nick => $data) {
			$a[$nick] = $data['name'];
        }
		asort($a);

		$this->allUsersCache = $a;
		return $a;
	}
    
    private function get_hidden_groups() {
		$groups_s = $this->model->action->getConf('hidden_groups');
		$groups = explode(',', $groups_s);
        
		foreach($groups as &$group) {
            $group = trim($group);
        }
        
		return $groups;
	}
    
    public function get_groups() {
		global $auth;
		$wikiusers = $auth->retrieveUsers();
		$groups = array();
		foreach ($wikiusers as $data) {
			$groups = array_merge($groups, $data['grps']);
		}
		$groups = array_unique($groups);
        
		$groups = array_diff($groups, $this->get_hidden_groups());
		
		sort($groups);
		
		return $groups;
	}
    
    public function users_of_group($groups) {
		$wikiusers = $this->model->dw_auth->retrieveUsers();
		if (is_string($groups)) {
		    $groups = array($groups);
        }

		return array_keys(array_filter($wikiusers, function($data) use ($groups) {
           return count(array_intersect($groups, $data['grps'])) > 0;
        }));
	}
	
	public function exists($nick) {
        if (!is_string($nick)) {
            return false;
        }

		// Lookup directo sin cargar todos los usuarios
		$userData = $this->model->dw_auth->getUserData($nick);
		return ($userData !== false);
	}

	public function get_user_full_name($nick) {
		// Lookup directo sin cargar todos los usuarios
		$userData = $this->model->dw_auth->getUserData($nick);
		return ($userData !== false && isset($userData['name'])) ? $userData['name'] : '';
	}
	
	public function get_user_email($nick) {
		$userData = $this->model->dw_auth->getUserData($nick);
		return ($userData !== false && isset($userData['mail'])) ? $userData['mail'] : '';
	}
}
