<?php

namespace App\Libraries\Cloudflare;

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


class Zone extends Cloudflare
{
    private $_model = null;
    private $_account_entity = null;
    private $_setting_fields = ['development_mode' => 'off', 'ipv6' => 'off', 'security_level' => 'medium'];
    public function __construct(AccountEntity $account_entity)
    {
        $this->_account_entity = $account_entity;
        $auth_entity = $this->getAuthModel()->getEntityByPK($this->_account_entity->getParent());
        if ($auth_entity === null) {
            throw new \Exception("해당 계정정보를 찾을수 없습니다.");
        }
        parent::__construct($auth_entity);
    }
    protected function getModel(): ZoneModel
    {
        if ($this->_model === null) {
            $this->_model = new ZoneModel();
        }
        return $this->_model;
    }
    protected function getArrayByResult($result, array $formDatas = []): array
    {
        $formDatas[ZoneModel::PK]     = $result->id;
        $formDatas[ZoneModel::PARENT] = $result->account->id;
        $formDatas[ZoneModel::TITLE]  = $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['updated_at'] = date("Y-m-d H:i:s");
        $formDatas['created_at'] = $result->created_on;
        $formDatas['plan']       = $result->plan->name;
        return $formDatas;
    }
    //Cfzone에서 가져온 값을 zone에 setting
    private function getCFSetting(ZoneEntity $entity): array
    {
        $cf = $this->getMySocket()->get('zones/' . $entity->getPK() . '/settings');
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Zone:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        $formDatas = [];
        foreach ($cf->result as $cf) {
            if (in_array($cf->id, array_keys($this->_setting_fields))) {
                $formDatas[$cf->id] = $cf->value;
            }
        }
        return $formDatas;
    }
    private function setCFSetting(ZoneEntity $entity, string $field, string $value): string
    {
        $datas = ['value' => $value];
        $cf = $this->getMySocket()->patch('zones/' . $entity->getPK() . '/settings/' . $field, $datas);
        $cf = json_decode($cf->getBody());
        if (!$cf->success || $cf->result->id !== $field) {
            $message = "Zone:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //최종 결과값은 body->result->id='필드명',body->result->value='on/off'이런식으로 받음
        return $cf->result->value;
    }
    public function create(string $domain, bool $jump_start = false): ZoneEntity
    {
        //Socket용
        //도메인생성을 위해 Cloudflare에 전송
        $datas = [
            'accountId'  => $this->_account_entity->getPK(),
            'name'       => $domain,
            'jump_start' => $jump_start,
        ];
        $cf = $this->getMySocket()->post('zones/', $datas);
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Zone:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //DB생성
        $formDatas = $this->getArrayByResult($cf->result);
        $entity    = $this->getModel()->create($formDatas);

        //초기화값 추가셋팅 ipv6 , development_mode , security_level
        $formDatas = [];
        foreach ($this->_setting_fields as $field => $default) {
            $formDatas[$field] = $this->setCFSetting($entity, $field, $default);
        }
        //DB수정
        return $this->getModel()->modify($entity, $formDatas);
    }
    public function modify(ZoneEntity $entity, array $formDatas): ZoneEntity
    {
        // throw new \Exception("zone:modify" . var_export($formDatas, true));
        //modify,toggle,batchjob 사용 셋팅 ipv6 , //development_mode , //security_level
        foreach ($formDatas as $field => $value) {
            $formDatas[$field] = $this->setCFSetting($entity, $field, $value);
        }
        //DB수정
        return $this->getModel()->modify($entity, $formDatas);
    }
    public function delete(ZoneEntity $entity): ZoneEntity
    {
        $cf = $this->getMySocket()->delete("zones/{$entity->getPK()}");
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Zone:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //DB삭제
        $this->getModel()->where(ZoneModel::PK, $entity->getPK());
        $this->getModel()->delete();
        return $entity;
    }
    public function sync(ZoneEntity $entity): ZoneEntity
    {
        $cf = $this->getMySocket()->get("zones/{$entity->getPK()}");
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Zone:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        $formDatas     = $this->getArrayByResult($cf->result);
        $entity        = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas);
        //추가 셋팅용
        $formDatas = $this->getCFSetting($entity);
        return $this->getModel()->modify($entity, $formDatas);
    }
    //Reload
    public function reload(): array
    {
        log_message("notice", "-----{$this->_account_entity->getTitle()} 처리 시작-----");
        $entitys = [];
        foreach ($this->reload_procedure('zones') as $result) {
            $formDatas     = $this->getArrayByResult($result);
            $entity        = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas);
            //추가 셋팅용
            $formDatas = $this->getCFSetting($entity);
            $entity = $this->getModel()->modify($entity, $formDatas);
            $entitys[$entity->getPK()] = $entity;
        }
        //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용
        $this->getModel()->where(ZoneModel::PARENT, $this->_account_entity);
        $this->getModel()->whereNotIn(ZoneModel::PK, array_keys($entitys));
        $this->getModel()->delete();
        log_message("notice", "-----{$this->_account_entity->getTitle()} 처리[" . count($entitys) . "개] 완료-----");
        return $entitys;
    }
}
