<?php

namespace App\Libraries\MyCloudflare;

use Cloudflare\API\Adapter\Guzzle;
use App\Models\Cloudflare\RecordModel;
use App\Libraries\MyCloudflare\MyCloudflare;
use App\Entities\Cloudflare\ZoneEntity;
use App\Entities\Cloudflare\RecordEntity;
use App\Entities\Cloudflare\AccountEntity;

class Record extends MyCloudflare
{
    private $_myStorage = null;
    private $_account_entity = null;
    private $_zone_entity = null;
    public function __construct(AccountEntity $account_entity, ZoneEntity $zone_entity)
    {
        parent::__construct();
        $this->_account_entity = $account_entity;
        $this->_zone_entity    = $zone_entity;
    }
    protected function getRequest(): Guzzle
    {
        return $this->getMySocket()->request($this->_account_entity->getAuthKey());
    }
    final protected function getMyStorage(): RecordModel
    {
        if ($this->_myStorage === null) {
            $this->_myStorage = new RecordModel();
        }
        return $this->_myStorage;
    }
    protected function getArrayByResult($result, array $formDatas = []): array
    {
        $formDatas[$this->getMyStorage()->getPKField()]    = $result->id;
        $formDatas[$this->getMyStorage()::PARENT]          = $result->zone_id;
        $formDatas[$this->getMyStorage()->getTitleField()] = $result->name;
        $formDatas['type']                                 = $result->type;
        $formDatas['content']                              = $result->content;
        $formDatas['ttl']                                  = (int)$result->ttl;
        $formDatas['proxiable']                            = $result->proxiable ? "on" : "off";
        $formDatas['proxied']                              = $result->proxied ? "on" : "off";
        $formDatas['locked']                               = "on";
        if (isset($result->locked) && $result->locked) {
            $formDatas['locked'] = "off";
        }
        // $formDatas['updated_at'] = $cfResult->modified_on;
        $formDatas['created_at'] = $result->created_on;
        return $formDatas;
    }
    public function create(string $host, array $formDatas): RecordEntity
    {
        //Socket용
        //도메인생성을 위해 Cloudflare에 전송
        $cf = $this->getRequest()->post('zones/' . $this->_zone_entity->getPK() . '/dns_records', [
            'name'    => $host,
            'type'    => $formDatas['type'],
            'content' => $formDatas['content'],
            'proxied' => isset($formDatas['proxied']) && $formDatas['proxied'] === 'on' ? true : false
        ]);
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        //Storage용
        $formDatas = $this->getArrayByResult($cf->result);
        $entity    = $this->$this->getMyStorage()->create($formDatas);
        log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
        return $entity;
    }
    public function modify(RecordEntity $entity, array $formDatas): RecordEntity
    {
        //TTL값은 CDN(proxied)가 사용함일때는 무조건 1, 않함일때는 120이 적용
        $datas = [
            'type'    => isset($formDatas['type']) ? $formDatas['type'] : $entity->type,
            'name'    => isset($formDatas['host']) ? $formDatas['host'] : $entity->host,
            'content' => isset($formDatas['content']) ? $formDatas['content'] : $entity->content,
            'proxied' => $entity->proxied == 'on' ? true : false,
            'ttl'     => intval($entity->ttl),
        ];
        //변경작업: 2024-08-09 
        if (isset($formDatas['proxied']) && $formDatas['proxied'] === 'on') {
            $datas['proxied'] = true;
            $datas['ttl']     = 1;
        } elseif (isset($formDatas['proxied']) && $formDatas['proxied'] === 'off') {
            $datas['proxied'] = false;
            $datas['ttl']     = 120;
        }
        $cf = $this->getRequest()->put('zones/' . $this->_zone_entity->getPK() . '/dns_records', $datas);
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
        return $entity;
    }
    public function delete(RecordEntity $entity): void
    {
        $cf = $this->getRequest()->delete('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK());
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
    }
    public function sync(RecordEntity $entity): RecordEntity
    {
        $cf = $this->getRequest()->get('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK());
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
        }
        log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
        $formDatas = $this->getArrayByResult($cf->result);
        return $this->$this->getMyStorage()->create($formDatas);
    }
    protected function reload_entity($cf): RecordEntity
    {
        return $this->getMyStorage()->modify(new RecordEntity, $this->getArrayByResult($cf));
    }
    public function reload(): void
    {
        $cfs = $this->reload_cfs($this->getRequest(), 'zones/' . $this->_zone_entity->getPK() . '/dns_records');
        log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($cfs) . "개] 시작-----");
        $entitys = $this->reload_entitys($this->_zone_entity->getPK(), $cfs);
        log_message("notice", "-----{$this->_zone_entity->getTitle()} DB 처리[" . count($entitys) . "개] 완료-----");
    }
}
