<?php

namespace AuthStack\Driver\LDAP;


use AuthStack\Driver\Errors\ConnectionError;
use AuthStack\Driver\Model\User;
use function Buckhill\config as cfg;
use AuthStack\Driver\Model\User as UserModel;
use AuthStack\Driver\Errors\NoAuthSourceError;
use AuthStack\Driver\Errors\InsufficientCredentialsError;
use Buckhill\LDAP\Client;

abstract class AbstractDriver
{
    /**
     * @var string
     */
    protected $cfg_key;

    /**
     * @var User
     */
    protected $user;

    /**
     * @var User
     */
    protected $provisioned;

    /**
     * @var null|int
     */
    protected $authsource_id = null;

    /**
     * @var null|Client
     */
    protected $ldap;

    /**
     * @var
     */
    protected $rdn;

    /**
     * @var
     */
    protected $filter;

    /**
     * @var string
     */
    protected $last_error = '';

    /**
     * @param      $key
     * @param int|null $authsource_id
     *
     * @return static
     */
    public static function initialize($key, $authsource_id)
    {
        $me = new static();

        $me->cfg_key = $key;

        return $me->setAuthSourceId($authsource_id);
    }

    /**
     * @return bool
     */
    public function connect()
    {
        if(!$this->ldap instanceof Client)
        {
            $this->ldap = new Client(
                $this->config('connection.host'),
                $this->config('connection.port'),
                $this->config('connection.options', []),
                $this->config('connection.TLS', false)
            );

            $this->ldap->connect();
        }

        return true;
    }


    /**
     * We don't need to elevate privileges using MySQL usually, so we'll leave this method to return true
     *
     * @return bool
     */
    public function elevate()
    {
        $conn   = $this->getConnection();

        return $conn->authenticate($this->config('connection.username'), $this->config('connection.password'));
    }

    /**
     * @return Client|null
     * @throws ConnectionError
     */
    public function getConnection()
    {
        if(!$this->ldap instanceof Client)
        {
            throw new ConnectionError('No active LDAP connection found.');
        }

        return $this->ldap;
    }

    /**
     * @param callable $callback
     * @return mixed
     */
    public function elevated(callable $callback)
    {
        $this->elevate();

        return $callback();
    }

    /**
     * @param $username
     * @return string|bool
     */
    public function getDN($username)
    {
        return $this->elevated(function() use ($username)
        {
            $uid        = $this->config('user_auth.uid');
            $dc         = $this->config('user_auth.dc');
            $username   = trim($username);

            $filter = sprintf("(%s=%s)", $uid, ldap_escape($username, null, LDAP_ESCAPE_FILTER));

            $ou         = $this->getOrganizationalUnits();

            $result = false;

            foreach($ou as $unit)
            {
                $base_dn = sprintf("%s,%s", $unit, $dc);

                $dn = $this->fetchDN($base_dn, $filter);

                if(false !== $dn)
                {
                    $result = $dn;

                    $this->rdn = $base_dn;
                    $this->filter = $filter;

                    break;
                }
            }

            return $result;
        });
    }

    /**
     * @return mixed
     */
    public function getUserRDN()
    {
        return $this->rdn;
    }

    /**
     * @return mixed
     */
    public function getUserFilter()
    {
        return $this->filter;
    }

    /**
     * @return array
     */
    public function getOrganizationalUnits()
    {
        $ou         = $this->config('user_auth.ou', '');

        $result     = is_array($ou) ? $ou : [$ou];

        return $result;
    }

    /**
     * Fetches distinguished name (DN) from filter result, if any. Returns false on failure
     *
     * @param $base
     * @param $filter
     * @return bool|string
     */
    public function fetchDN($base, $filter)
    {
        $connection = $this->getConnection()->getConnection();

        $dn = false;

        try
        {
            $result = @ldap_search($connection, $base, $filter);

            if(false !== $result)
            {
                $first  = @ldap_first_entry($connection, $result);
                $dn     = @ldap_get_dn($connection, $first);

                // This line is required for reasons. And reasons are dragons and we don't touch dragons.
                // Now for real: the result of ldap_get_dn can be empty, even if search filter is successful
                // That's why we need another check, so that the callee can repeat this function
                if(empty($dn))
                {
                    $dn = false;
                }
            }
            else
            {
                $this->last_error = 'No such entry in directory ' . ldap_error($connection);
            }
        }
        catch(\Exception $e)
        {
            $this->last_error = $e->getMessage();
        }

        return $dn;
    }

    /**
     * @param $id
     *
     * @return $this
     */
    public function setAuthSourceId($id)
    {
        $this->authsource_id = $id;

        return $this;
    }

    /**
     * @return int|null
     *
     * @throws NoAuthSourceError
     */
    public function getAuthSourceId()
    {
        if (is_null($this->authsource_id)) {
            throw new NoAuthSourceError('No authsource_id has been set. Unable to retrieve authsource_id.');
        }

        return $this->authsource_id;
    }

    /**
     * @return string
     */
    public function lastError()
    {
        return $this->last_error;
    }

    /**
     * @param $username
     *
     * @throws NoAuthSourceError
     */
    protected function provision($username)
    {
        $this->provisioned = UserModel::retrieve([
            'conn_id' => $this->getAuthSourceId(),
            'username' => $username
        ]);
    }

    /**
     * @return UserModel
     */
    protected function getProvisionedUser()
    {
        return $this->provisioned;
    }

    /**
     * @param array $credentials
     *
     * @throws InsufficientCredentialsError
     */
    protected function check(array $credentials)
    {
        if (!isset($credentials['username'])) {
            throw new InsufficientCredentialsError('Insufficient credentials: username is required');
        }

        if (!isset($credentials['password'])) {
            throw new InsufficientCredentialsError('Insufficient credentials: password is required');
        }
    }

    /**
     * @param $username
     *
     * @return string
     */
    protected function getUniqueId($username)
    {
        return sha1(sprintf("%d.%s", $this->getAuthSourceId(), $username), true);
    }

    /**
     * @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);
    }
}