<?php

namespace App\Libraries\MyCloudflare;

use App\Models\Cloudflare\ZoneModel;
use App\Libraries\MyCloudflare\MyCloudflare;
use App\Entities\Cloudflare\ZoneEntity;
use App\Entities\Cloudflare\AccountEntity;

use Cloudflare\API\Adapter\Guzzle;

class Zone extends MyCloudflare
{
    private $_myStorage = null;
    private $_account_entity = null;
    public function __construct(AccountEntity $account_entity)
    {
        parent::__construct();
        $this->_account_entity = $account_entity;
    }
    private function getRequest(): Guzzle
    {
        return $this->getMySocket()->request($this->_account_entity->getAuthKey());
    }
    final protected function getMyStorage(): ZoneModel
    {
        if ($this->_myStorage === null) {
            $this->_myStorage = new ZoneModel();
        }
        return $this->_myStorage;
    }
    protected function getArrayByResult($result, array $formDatas = []): array
    {
        $formDatas[$this->getMyStorage()->getPKField()]    = $result->id;
        $formDatas[$this->getMyStorage()::PARENT]          = $result->account->id;
        $formDatas[$this->getMyStorage()->getTitleField()] = $result->name;
        $formDatas['status']                               = $result->status;
        //$formDatas['type'] = $result->type; // full 이게있는데 뭔지 잘모름
        $formDatas['name_servers'] = 'none';
        if (isset($result->name_servers)) {
            $formDatas['name_servers'] = is_array($result->name_servers) ?
                implode(
                    ',',
                    $result->name_servers
                ) : $result->name_servers;
        }
        $formDatas['original_name_servers'] = 'none';
        if (isset($result->original_name_servers)) {
            $formDatas['original_name_servers'] = is_array($result->original_name_servers) ?
                implode(
                    ',',
                    $result->original_name_servers
                ) : $result->original_name_servers;
        }
        $formDatas['updated_at'] = $result->modified_on;
        $formDatas['created_at'] = $result->created_on;
        $formDatas['plan']       = $result->plan->name;
        return $formDatas;
    }
    //Cfzone에서 가져온 값을 zone에 setting
    final public function getCFSetting(ZoneEntity $entity): ZoneEntity
    {
        $cf = $this->getRequest()->patch('zones/' . $entity->getPK() . '/settings/');
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        foreach ($cf->result as $cf) {
            switch ($cf->id) {
                case 'development_mode':
                    $entity->development_mode = $cf->value;
                    break;
                case 'ipv6':
                    $entity->ipv6 = $cf->value;
                    break;
                case 'security_level':
                    $entity->security_level = $cf->value;
                    break;
            }
        }
        return $entity;
    }
    final public function setCFSetting(ZoneEntity $entity, string $field, string $value): ZoneEntity
    {
        $cf = $this->getRequest()->patch('zones/' . $entity->getPK() . '/settings/' . $field, array('value' => $value));
        $cf = json_decode($cf->getBody());
        if (!$cf->success || $cf->result->id !== $field) {
            throw new \Exception("Zone:" . __FUNCTION__ . "에서 {$field}->{$value} 변경실패:\n" . var_export($cf, true));
        }
        //최종 결과값은 body->result->id='필드명',body->result->value='on/off'이런식으로 받음
        $entity->$field = $cf->result->value;
        return $entity;
    }
    public function create(string $domain, bool $jump_start = false): ZoneEntity
    {
        //Socket용
        //도메인생성을 위해 Cloudflare에 전송
        $cf = $this->getRequest()->post('zones/', [
            'accountId'  => $this->_account_entity->getPK(),
            'name'       => $domain,
            'jump_start' => $jump_start,
        ]);
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        //Storage용
        $formDatas = $this->getArrayByResult($cf->result);
        $entity    = $this->$this->getMyStorage()->create($formDatas);
        //아래는 추가 셋팅 ipv6 TurnOFF , //Development mode TurnOFF
        $entity = $this->setCFSetting($entity, 'ipv6', 'off');
        $entity = $this->setCFSetting($entity, 'development_mode', 'off');
        $entity = $this->setCFSetting($entity, 'security_level', 'medium');
        log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
        return $entity;
    }
    public function modify(ZoneEntity $entity, array $formDatas): ZoneEntity
    {
        //ipv6 , //development_mode , //security_level
        foreach ($formDatas as $field => $value) {
            $entity = $this->setCFSetting($entity, $field, $value);
        }
        log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
        return $entity;
    }
    public function delete(ZoneEntity $entity): void
    {
        $cf = $this->getRequest()->delete('zones/' . $entity->getPK());
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
    }
    public function sync(ZoneEntity $entity): ZoneEntity
    {
        $cf = $this->getRequest()->get('zones/' . $entity->getPK());
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
        $formDatas = $this->getArrayByResult($cf->result);
        return $this->$this->getMyStorage()->create($formDatas);
    }
    protected function reload_entity($cf): ZoneEntity
    {
        return $this->getMyStorage()->modify(new ZoneEntity, $this->getArrayByResult($cf));
    }
    public function reload(): void
    {
        $cfs = $this->reload_cfs($this->getRequest(), 'zones');
        log_message("notice", "-----{$this->_account_entity->getTitle()} 처리[" . count($cfs) . "개] 시작-----");
        $entitys = $this->reload_entitys($this->_account_entity->getPK(), $cfs);
        log_message("notice", "-----{$this->_account_entity->getTitle()} DB 처리[" . count($entitys) . "개] 완료-----");
    }
}
