<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Api\Controller;

use Sso\WebserviceBundle\Api;
use Sso\WebserviceBundle\Api\Exception\Type\Api as ApiException;
use Sso\WebserviceBundle\Api\Error\Type\External as ExternalError;
use Sso\WebserviceBundle\Api\Error\Type\Internal as InternalError;
use Sso\WebserviceBundle\Api\Response\Builder as XmlResponse;

/**
 * Class IndexController
 * @package Sso\WebserviceBundle\Api\Controller
 */
class IndexController
{
    /**
     * List of available controllers
     * @var array
     */
    protected $_controllerList = array(
        'Application',
        'ApplicationRole',
        'ApplicationAttribute',
        'User',
        'UserApplication',
        'UserApplicationAttribute',
        'UserApplicationRole',
        'UserSearch',
        'UserService',
    );

    /**
     * Current controller name
     *
     * @var string
     */
    private $_controllerName = 'Unknown';

    /**
     * Current action name
     *
     * @var string
     */
    private $_actionName = 'Unknown';

    /**
     * Controller node in xml document
     *
     * @var \SimpleXMLElement
     */
    private $_xmlController;

    /**
     * Credentials node in xml document
     *
     * @var \SimpleXMLElement
     */
    private $_xmlCredentials;

    /**
     * Request xml
     *
     * @var \SimpleXMLElement
     */
    public $simpleXML = false;

    /**
     * Api-Manager
     *
     * @var Api\Manager
     */
    public $apiM;

    /**
     *
     * @var Api\Error\Storage
     */
    public $apiErrors;

    /**
     * Constructor
     *
     * @param Api\Manager $apiM
     */
    public function __construct(Api\Manager $apiM)
    {
        $this->apiM = $apiM;
        $this->apiErrors = new Api\Error\Storage();
    }

    /**
     * Exit with error
     *
     * @param Api\Error\Type\Base $error
     * @throws ApiException
     */
    private function _exception(Api\Error\Type\Base $error = null)
    {
        if (null !== $error) {
            $this->apiErrors->addError($error);
        }
        $exception = new ApiException();
        $exception->setErrors($this->apiErrors->getErrors());
        throw $exception;
    }

    /**
     * Get crontroler object
     *
     * @param string $controllerName
     * @param string $actionName
     * @param string $xmlRequest
     * @param XmlResponse $xmlResponse
     * @param string $remoteAddress
     * @return AbstractController
     */
    public function getController($controllerName, $actionName, $xmlRequest, XmlResponse $xmlResponse)
    {

        $this->_actionName = (string)$actionName;
        $this->_controllerName = (string)$controllerName;

        $this->simpleXML = simplexml_load_string($xmlRequest, "SimpleXMLElement", LIBXML_COMPACT);

        // Check xml structure
        $this->_validateXmlElements();

        ApiException::setController($this->_controllerName);
        ApiException::setAction($this->_actionName);

        $className = __NAMESPACE__.'\\'.$controllerName.'Controller';

        return new $className($this->apiM, $this->_xmlController, $xmlResponse);
    }


    /**
     * Validate xml structure and read controller and credentials from xml
     */
    private function _validateXmlElements()
    {
        $xmlElementCnt = 0;
        foreach ($this->simpleXML as $root) {
            switch ($xmlElementCnt) {
                case 0:
                    $this->_xmlCredentials = $root;
                    break;
                case 1:
                    $this->_xmlController = $root;
                    break;
                default:
                    $this->_exception(new ExternalError('xh01', 'XmlInvalid', 'Too many nodes in xml'));
            }
            ++$xmlElementCnt;
        }

        // Check controller node
        if (null === $this->_xmlController) {
            $this->_exception(new ExternalError('xh03', 'ControllerNotFound'));
        }
    }
}
