<?php

namespace models;

use Illuminate\Contracts\Support\Arrayable;
use models\dataMappers\LdapUserAdapterInterface;

class LdapUserAdapter implements Arrayable, LdapUserAdapterInterface
{
    /**
     * @var $ldapUser \LdapRecord\Models\Entry
     */
    private $ldapUser;
    private $config;

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

    public function setLdapUser(\LdapRecord\Models\Entry $user){
        $this->ldapUser = $user;
    }

    public function getEmail()
    {
        return $this->ldapUser->mail[0] ?? '';
    }

    public function getId()
    {
        return $this->ldapUser->getAttribute(strtolower($this->config['login_attribute']))[0] ?? '';
    }

    public function getGroups()
    {

        $groups = [];
        if (!empty($this->config['group_attribute'])) {
            $memberOf = $this->ldapUser->getAttribute((strtolower($this->config['group_attribute'])));
            if (!empty($memberOf)) {
                foreach ($memberOf as $group) {
                    // get common name from base DN
                    if (preg_match('/cn=(.+?),/i', $group, $matches)) {
                        $groups[] = $matches[1];
                    }
                }
            }
        }
        return $groups;
    }

    public function toArray()
    {
        return [
            'id' => $this->getId(),
            'email' => $this->getEmail(),
            'roles' => $this->getGroups()
        ];
    }
}