<?php

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

/**
 * Description of CheckMoreDomains
 *
 * @author Rafał Ossowski <rafal.os@modulesgarden.com>
 */
class CheckMoreDomains extends AbstractMethod
{
    protected $domainList = [];
    protected $returnData = [];

    public function execute($records)
    {
        foreach ($this->getDomainList($records) as $domain => $tlds)
        {
            $response = $this->request->process(
                'json', json_encode([
                    'func' => 'fastDomainLookup',
                    'data' => [
                        'domain'     => $this->idnaConvert->encode(strtolower($domain)),
                        'selected'   => implode(';', $tlds),
                        'alldomains' => implode(';', $tlds)
                    ]
                ])
            )->resultFormatted;

            $this->returnData = array_merge($this->returnData, json_decode($response));
        }

        return $this->formatResponse();
    }

    protected function getDomainList($records = [])
    {
        $this->domainList = [];
        foreach ($records as $record)
        {
            $this->domainList[$record['sld']][] = "." . $this->idnaConvert->encode(strtolower($record['tld']));
        }

        return $this->domainList;
    }

    protected function formatResponse()
    {
        $returnData = [];
        foreach ($this->returnData as $record)
        {
            $returnData[] = [
                'sld'    => $this->idnaConvert->decode($record->domain),
                'tld'    => $this->idnaConvert->decode($record->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;
        }
    }
}
