<?php

namespace App\Controllers\Admin\Cloudflare;

use App\Entities\Cloudflare\RecordEntity;
use App\Helpers\Cloudflare\ZoneHelper;
use App\Libraries\Cloudflare\Record;
use App\Libraries\Cloudflare\Zone;
use App\Models\Cloudflare\ZoneModel;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class ZoneController extends CloudflareController
{
    private $_myLibrary = null;
    private $_account_entity = null;
    private $_model = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->class_name .= "Zone";
        $this->class_path .= $this->class_name;
        $this->title      = lang("{$this->class_path}.title");
        $this->helper     = new ZoneHelper();
    }
    final protected function getModel(): ZoneModel
    {
        if ($this->_model === null) {
            $this->_model = new ZoneModel();
        }
        return $this->_model;
    }
    final protected function getMyLibrary(): Zone
    {
        if ($this->_myLibrary === null) {
            $this->_myLibrary = new Zone($this->_account_entity);
        }
        return $this->_myLibrary;
    }
    protected function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            case $this->getModel()::PARENT:
                // $this->getAccountModel()->where('status', DEFAULTS['STATUS']);
                $options[$field] = $this->getAccountModel()->getFormFieldOption($field);
                // echo $this->getAccountModel()->getLastQuery();
                // dd($options);
                break;
            case 'type':
            case 'proxied':
                $options[$field] = lang('Cloudflare/Record.' . strtoupper($field));
                break;
            default:
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    protected function getFormData(string $field, array $formDatas): array
    {
        switch ($field) {
            case 'domains':
                $formDatas[$field] = explode("\n", $this->request->getVar($field));
                if (!is_array($formDatas[$field]) || !count($formDatas[$field])) {
                    throw new \Exception("도메인명이 정의되지 않았습니다.");
                }
                break;
            case 'hosts':
                $formDatas[$field] = $this->request->getVar($field);
                if (!is_array($formDatas[$field]) || !count($formDatas[$field])) {
                    throw new \Exception("호스트명이 정의되지 않았습니다");
                }
                break;
            default:
                $formDatas = parent::getFormData($field, $formDatas);
                break;
        }
        return $formDatas;
    }
    private function init(string $action): void
    {
        $this->action = $action;
        $this->fields = [$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied'];
        $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields);
        $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied'];
        $this->field_options = $this->getFormFieldOptions($this->filter_fields);
    }
    //생성
    public function create_form(): RedirectResponse|string
    {
        $this->init('create');
        $parent_field = $this->getModel()::PARENT;
        $this->$parent_field = $this->request->getVar($parent_field) ?: DEFAULTS["EMPTY"];
        return $this->create_form_procedure();
    }
    protected function create_validate(string $action, array $fields): void
    {
        //domains,hosts를 제외한 fields Valid처리
        parent::create_validate($action, array_diff($fields, ['domains', 'hosts']));
    }
    protected function create_process(): void
    {
        //DB작업도 Socket에서 다 처리하므로 parent::create_process()하면 않됨
        $this->create_validate($this->action, $this->fields);
        $this->formDatas = $this->getFormDatas();
        //부모데이터 정의
        $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]);
        //데이터검증
        //Type이 A형식일경우 IP형태인지 확인
        if ($this->formDatas['type'] === 'A') {
            if (!$this->helper->isIPAddress($this->formDatas['content'], $this->formDatas['type'])) {
                throw new \Exception("{$this->_account_entity->getTitle()}의 {$this->formDatas['type']}, {$this->formDatas['content']} 형식 오류[사설IP 않됨]");
            }
        }
        $cnt = 1;
        foreach ($this->formDatas['domains'] as $domain) {
            //도메인명 형식확인
            if (!$this->helper->isDomain($domain)) {
                throw new \Exception("{$this->_account_entity->getTitle()}의 {$cnt}번째 {$domain} 형식 오류");
            }
            //도메인명이 해당계정의 유일한 도메인인지 확인
            if (!$this->getModel()->isUniqueDomain($this->_account_entity, $domain)) {
                throw new \Exception("{$this->_account_entity->getTitle()}의 {$cnt}번째 {$domain}은 이미 등록된 도메인입니다.");
            }
            $cnt++;
        }
        $cnt = 1;
        foreach ($this->formDatas['hosts'] as $host) {
            //호스트명 형식확인
            if (!$this->helper->isHost($host)) {
                throw new \Exception("{$this->_account_entity->getTitle()}의 {$cnt}번째 {$host} 호스트명 형식 오류");
            }
            $cnt++;
        }
        //Socket처리
        //Zone생성
        $cnt = 1;
        $zone_entitys = [];
        foreach ($this->formDatas['domains'] as $domain) {
            $entity = $this->getMyLibrary()->create($domain);
            log_message("debug", "Zone:{$entity->getTitle()} 작업을 완료하였습니다.");
            $zone_entitys[] = $entity;
            $cnt++;
        }
        //Record생성
        foreach ($zone_entitys as $zone_entity) {
            $record = new Record($zone_entity);
            foreach ($this->formDatas['hosts'] as $host) {
                $entity = $record->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']);
                log_message("debug", "Record:{$entity->getTitle()} 작업을 완료하였습니다.");
            }
        }
    }
    public function create(): RedirectResponse|string
    {
        $this->init(__FUNCTION__);
        return $this->create_procedure();
    }
    //수정 (modify,toggle,batchjob사용)
    protected function modify_process(string $uid): void
    {
        //DB작업도 Socket에서 다 처리하므로 parent::modify_process($uid)하면 않됨
        $this->modify_validate($this->action, $this->fields);
        $this->formDatas = $this->getFormDatas();
        //자신정보정의
        $this->entity = $this->getModel()->getEntityByPK($uid);
        if ($this->entity === null) {
            throw new \Exception("{$uid} 정보를 찾을수 없습니다.");
        }
        //부모데이터정의
        $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->entity->getParent());
        //Socket처리
        $this->entity = $this->getMyLibrary()->modify($this->entity, $this->formDatas);
    }
    //일괄처리작업
    public function batcjob(): RedirectResponse
    {
        $this->action = __FUNCTION__;
        $this->fields = ['development_mode', 'ipv6', 'security_level'];
        $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields);
        return $this->batcjob_procedure();
    }
    //Sync작업
    protected function sync_process(mixed $uid): void
    {
        //자신정보정의
        $this->entity = $this->getModel()->getEntityByPK($uid);
        if ($this->entity === null) {
            throw new \Exception("{$uid} 정보를 찾을수 없습니다.");
        }
        //부모데이터정의
        $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->entity->getParent());
        //Socket처리
        $this->entity = $this->getMyLibrary()->sync($this->entity);
    }
    public function sync(string $uid): RedirectResponse
    {
        return $this->sync_procedure($uid);
    }
    //삭제
    protected function delete_process(string $uid): void
    {
        //DB작업도 Socket에서 다 처리하므로 parent::delete_process($uid)하면 않됨
        //자신정보정의
        $this->entity = $this->getModel()->getEntityByPK($uid);
        if ($this->entity === null) {
            throw new \Exception("{$uid} 정보를 찾을수 없습니다.");
        }
        //부모데이터정의
        $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]);
        //Cloudflare 삭제
        $this->entity = $this->getMyLibrary()->delete($this->entity);
    }
    //  리스트
    public function index(): string
    {
        $this->action = __FUNCTION__;
        $this->fields = [$this->getModel()::PARENT, $this->getModel()::TITLE, 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'created_at'];
        $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields);
        $this->filter_fields = [$this->getModel()::PARENT, 'development_mode', 'ipv6', 'security_level'];
        $this->field_options = $this->getFormFieldOptions($this->filter_fields);
        $this->batchjob_fields = ['development_mode', 'ipv6', 'security_level'];
        return $this->list_procedure();
    }
    // Download
    public function download(string $output_type, $uid = false): DownloadResponse|string
    {
        $this->action = __FUNCTION__;
        $this->fields = [$this->getModel()::PARENT, $this->getModel()::TITLE, 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'created_at'];
        $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields);
        $this->filter_fields = [$this->getModel()::PARENT, 'development_mode', 'ipv6', 'security_level'];
        $this->field_options = $this->getFormFieldOptions($this->filter_fields);
        $this->batchjob_fields = ['development_mode', 'ipv6', 'security_level'];
        return $this->download_procedure($output_type, $uid);
    }
    //reload Zone By Account
    protected function reload_process(mixed $uid): void
    {
        $this->_account_entity = $this->getAccountModel()->getEntityByPK($uid);
        if ($this->_account_entity === null) {
            throw new \Exception("Account: {$uid} 정보를 찾을수 없습니다.");
        }
        $this->getModel()->where($this->getModel()::PARENT, $this->_account_entity->getPK());
        foreach ($this->getModel()->getEntitys() as $entity) {
            $this->getMyLibrary()->reload();
        }
    }
    public function reload(string $uid): RedirectResponse
    {
        return $this->reload_procedure($uid);
    }
}
