<?php

namespace AuthStack\Driver\SOAP;


use AuthStack\Driver\Driver\AuthDriverInterface;
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;

/**
 * Class AbstractSOAP
 * @package AuthStack\Authentication\Drivers\SOAP
 * @mixin AuthDriverInterface
 */
abstract class AbstractSOAP
{
    /**
     * @var string
     */
    protected $cfg_key;
    /**
     * @var User
     */
    protected $user;
    /**
     * @var User
     */
    protected $provisioned;
    /**
     * @var null|int
     */
    protected $authsource_id = null;
    /**
     * @var string
     */
    protected $last_error = '';
    /**
     * @var Lib\SoapClient
     */
    protected $client;

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

        $me->cfg_key = $key;

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

    /**
     * @return bool
     */
    abstract public function connect();

    /**
     * SOAP Requests don't need privilege escalation so we're returning true
     * @return bool
     */
    public function elevate()
    {
        return true;
    }

    /**
     * @return Lib\SoapClient|null
     */
    abstract public function getConnection();

    /**
     * @param array $credentials
     *
     * @return bool
     */
    abstract public function authenticate(array $credentials);

    /**
     * @param $id
     *
     * @return AuthDriverInterface
     */
    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 string|int $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);
    }


}