<?php

namespace ModulesGarden\ProxmoxAddon\App\Libs\Api;

use ModulesGarden\ProxmoxAddon\App\Libs\Api\ENom\Parser;
use ModulesGarden\ProxmoxAddon\Core\Api\AbstractApi;
use ModulesGarden\ProxmoxAddon\Core\ModuleConstants;
use Mso\IdnaConvert\IdnaConvert;

/**
 * Description of ENom
 *
 * @author Rafał Ossowski <rafal.os@modulesgarden.com>
 */
class ENom extends AbstractApi
{
    const METHOD_API_CHECK_ONE_DOMAIN   = 'CheckOneDomain';
    const METHOD_API_CHECK_MORE_DOMAINS = 'CheckMoreDomains';
    protected $settings;
    protected $request;

    /**
     * @var IdnaConvert
     */
    protected $idnaConvert;

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

    public function setSettings($settings)
    {
        $this->settings = $settings;

        return $this;
    }

    public function checkMoreDomain($records)
    {
        return $this->loadRequest()->callToMethod(self::METHOD_API_CHECK_MORE_DOMAINS, $records);
    }

    protected function callToMethod($name, $params = null)
    {
        $namespace = "\\" . ModuleConstants::getRootNamespace() . "\App\Libs\Api\ENom\Method\\" . $name;
        return (new $namespace($this->request, $this->settings, $this->idnaConvert))->execute($params);
    }

    protected function loadRequest()
    {
        $this->request = $this->getNewRequest();
        $this->request->setCurlParser(new Parser())
            ->setUrl('https://' . $this->settings['hostname'] . '/interface.asp')
            ->resetHeaders();

        return $this;
    }

    public function checkOneDomain($record)
    {
        return $this->loadRequest()->callToMethod(self::METHOD_API_CHECK_ONE_DOMAIN, $record);
    }
}
