<?php

namespace ModulesGarden\ProxmoxAddon\App\Libs\Api\OpenSRS\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()
    {
        $tld = "." . $this->idnaConvert->encode(strtolower($this->tld));

        $response = $this->request->process(
            'json', json_encode([
                'func' => 'fastDomainLookup',
                'data' => [
                    'domain'     => $this->idnaConvert->encode(strtolower($this->domain)),
                    'selected'   => $tld,
                    'alldomains' => $tld,
                ]
            ])
        )->resultFormatted;

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

    protected function formatResponse($response)
    {
        $returnData = [];
        foreach (json_decode($response) as $record)
        {
            $returnData[] = [
                'sld'    => $this->domain,
                'tld'    => $this->tld,
                'status' => $this->choseResult($record->result)
            ];
        }
        return $returnData;
    }

    protected function choseResult($return)
    {
        switch ($return)
        {
            case 'Available':
                return self::RESPONSE_RESULT_FREE;
            case 'Taken':
                return self::RESPONSE_RESULT_TAKEN;
            default:
                return self::RESPONSE_RESULT_ERROR;
        }
    }
}
