<?php

namespace App\Libraries\MyCloudflare;

use Cloudflare\API\Adapter\Guzzle;
use App\Libraries\MySocket\CloudflareSocket;
use App\Libraries\CommonLibrary;

abstract class MyCloudflare extends CommonLibrary
{
    private $_mySocket = null;
    protected function __construct()
    {
        parent::__construct();
    }
    abstract protected function getArrayByResult($result, array $formDatas = []): array;
    abstract protected function reload_entity($cf): mixed;
    abstract protected function getMyStorage(): mixed;
    final protected function getMySocket(): CloudflareSocket
    {
        if ($this->_mySocket === null) {
            $this->_mySocket = new CloudflareSocket();
        }
        return $this->_mySocket;
    }
    //-----------------------필수항목-------------------//
    final protected function reload_entitys(string $parent, array $cfs): array
    {
        $entity_uids = [];
        if (count($cfs)) {
            $cnt = 1;
            foreach ($cfs as $cf) {
                $entity        = $this->reload_entity($cf);
                $entity_uids[] = $entity->getPK();
                log_message("debug", "{$cnt}번째: {$entity->getTitle()} 저장");
                $cnt++;
            }
            //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용
            $this->getMyStorage()->where($this->getMyStorage()::PARENT, $parent);
            $this->getMyStorage()->whereNotIn($this->getMyStorage()->getPKField(), $entity_uids);
            $this->getMyStorage()->delete();
        }
        return $entity_uids;
    }
    final protected function reload_cfs(Guzzle $request, $uri): array
    {
        $page        = 1; //Page는 1부터 시작해야함
        $perpage_max = getenv("cfmgr.request.perpage.max");
        $cfs         = [];
        do {
            $query = [
                'page'     => $page,
                'per_page' => $perpage_max,
                'match'    => 'all',
            ];
            $cf    = $request->get($uri, $query);
            $cf    = json_decode($cf->getBody());
            if (!$cf->success) {
                throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
            }
            $cfs = [$cfs, ...$cf->result];
            //Loop 제한 : 한페이지에서 가져온 갯수가 perpage_max보다 적다는것은 더이상 다음페이지기 없으므로 0로 종료시키기 위함
            $page = count($cf->result) < $perpage_max ? 0 : $page + 1;
        } while (0 < $page);
        return $cfs;
    }
}
