<?php

namespace ModulesGarden\ProxmoxAddon\App\Libs\Api\ENom\Method;

/**
 * Description of CheckOneDomain
 *
 * @author Rafał Ossowski <rafal.os@modulesgarden.com>
 */
class CheckOneDomain extends AbstractMethod
{
    protected $domain;
    protected $tld;

    public function execute($params)
    {
        $this->domain = str_replace(' ', '', $params['sld']);
        $this->tld    = $params['tld'];
        return $this->checkOneDomain();
    }

    public function checkOneDomain()
    {

        $response = $this->request->post([
            'Command'      => 'check',
            'SLD'          => $this->idnaConvert->encode(strtolower($this->domain)),
            'TLD'          => $this->idnaConvert->encode(strtolower(substr($this->tld, 1))),
            'ResponseType' => 'xml',
            'UID'          => $this->settings['username'],
            'PW'           => $this->settings['password'],
        ]);

        return $this->formatResponse($response);
    }

    protected function formatResponse($response)
    {
        $resultData = [];
        if ($response && $response->isSuccess())
        {
            $response = $response->getBody();
            $status   = ($response->Done == 'true') ? $this->getStatus((int)$response->RRPCode) : self::RESPONSE_RESULT_ERROR;
        }
        else
        {
            $status = self::RESPONSE_RESULT_ERROR;
        }
        $resultData[] = [
            'sld'    => $this->domain,
            'tld'    => $this->tld,
            'status' => $status
        ];

        return $resultData;
    }

    protected function getStatus($rRPCode)
    {
        $status = self::RESPONSE_RESULT_ERROR;
        switch ($rRPCode)
        {
            case 211:
                $status = self::RESPONSE_RESULT_TAKEN;
            case 210:
                $status = self::RESPONSE_RESULT_FREE;
        }
        return $status;
    }
}
