<?php

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

use ModulesGarden\ProxmoxAddon\Core\Helper\DomainHelper;

/**
 * Description of CheckMoreDomains
 *
 * @author Rafał Ossowski <rafal.os@modulesgarden.com>
 */
class CheckMoreDomains extends AbstractMethod
{

    public function execute($records)
    {
        $returnData = [];
        $domainList = $this->getDomainList($records);

        if (count($domainList) > 30)
        {
            while (!empty($domainList))
            {
                $returnData = array_merge(
                    $returnData, $this->checkDomainList(array_slice($domainList, 0, 30))
                );
                array_splice($domainList, 0, 30);
            }
        }
        else
        {
            $returnData = $this->checkDomainList($domainList);
        }

        return $returnData;
    }

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

        return $domainList;
    }

    protected function checkDomainList($domainList)
    {
        $response = $this->request->post([
            'Command'      => 'check',
            'DomainList'   => str_replace(' ', '', implode(',', $domainList)),
            'ResponseType' => 'xml',
            'UID'          => $this->settings['username'],
            'PW'           => $this->settings['password']
        ]);

        if ($response && $response->isSuccess())
        {
            $response = $response->getBody();
            if ($response->Done == 'true')
            {
                return $this->formatResponse($response);
            }
        }

        return false;
    }

    protected function formatResponse($response)
    {
        $result = [];
        foreach ($response as $key => $value)
        {
            switch ($key)
            {
                case 'DomainCount':
                case 'IsPremiumName':
                case 'PremiumPrice':
                case 'PremiumAboveThresholdPrice':
                case 'Command':
                case 'ErrCount':
                case 'ErrX':
                case 'Done':
                    continue;
                default :
                    $this->parserResponse($result, $this->convertDomain($key, $value));
            }
        }

        return $result;
    }

    protected function parserResponse(&$result, $data)
    {
        switch ($data['key'])
        {
            case 'Domain':
                $result[$data['name']]['sld'] = $data['value']->getDomain();
                $result[$data['name']]['tld'] = $data['value']->getTLDWithDot();
                break;
            case 'RRPCode':
                $result[$data['name']]['status'] = $data['value'];
                break;
        }
    }

    protected function convertDomain($key, $value)
    {
        $name = $this->getName($key);
        if (strpos($key, 'Domain') !== false)
        {
            $key   = 'Domain';
            $value = new DomainHelper($this->idnaConvert->decode($value));
        }
        elseif (strpos($key, 'RRPCode') !== false)
        {
            $key   = 'RRPCode';
            $value = $this->choseResult($value);
        }
        else
        {
            $key = null;
        }

        return [
            'name'  => $name,
            'key'   => $key,
            'value' => $value
        ];
    }

    protected function getName($key)
    {
        return substr($key, (strpos($key, 'Domain') !== false) ? 6 : 7);
    }

    protected function choseResult($value)
    {
        switch ($value)
        {
            case 210:
                return self::RESPONSE_RESULT_FREE;
            case 211:
                return self::RESPONSE_RESULT_TAKEN;
            default :
                return self::RESPONSE_RESULT_ERROR;
        }
    }
}
