<?php

namespace App\Libraries\Cloudflare;

use App\Models\Cloudflare\AccountModel;
use App\Entities\Cloudflare\AuthEntity;

class Account extends Cloudflare
{
    private $_model = null;
    public function __construct(AuthEntity $auth_entity)
    {
        parent::__construct($auth_entity);
    }

    protected function getModel(): AccountModel
    {
        if ($this->_model === null) {
            $this->_model = new AccountModel();
        }
        return $this->_model;
    }
    //Result 형태
    // [
    //   {"id":"078e88a7735965b661715af13031ecb0",
    //   "name":"Cloudwin002@idcjp.jp's Auth",
    //   "type":"standard",
    //   "settings":{
    //     "enforce_twofactor":false,
    //     "api_access_enabled":null,
    //     "access_approval_expiry":null,
    //     "use_account_custom_ns_by_default":false
    //   },
    //   "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}},
    //   "created_on":"2017-06-26T05:44:49.470184Z"}
    // ]
    public function getArrayByResult($result, array $formDatas = []): array
    {
        $formDatas[AccountModel::PK]    = $result->id;
        $formDatas[AccountModel::PARENT] = $this->getAuthEntity()->getPK();
        $formDatas[AccountModel::TITLE] = $result->name;
        $formDatas['type']              = $result->type;
        $formDatas['status']            = $this->getAuthEntity()->status;
        $formDatas['updated_at']        = date("Y-m-d H:i:s");
        $formDatas['created_at']        = $result->created_on;
        return $formDatas;
    }
    public function reload(): array
    {
        log_message("notice", "-----{$this->getAuthEntity()->getTitle()} 처리 시작-----");
        $entitys = [];
        foreach ($this->reload_procedure("accounts") as $result) {
            $formDatas     = $this->getArrayByResult($result);
            $entity        = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas);
            $entitys[$entity->getPK()] = $entity;
        }
        //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용
        $this->getModel()->where(AccountModel::PARENT, $this->getAuthEntity());
        $this->getModel()->whereNotIn(AccountModel::PK, array_keys($entitys));
        $this->getModel()->delete();
        log_message("notice", "-----{$this->getAuthEntity()->getTitle()} 처리[" . count($entitys) . "개] 완료-----");
        return $entitys;
    }
}
