<?php

/**
 * Save.php
 * 文件描述
 * Created On 2022/1/17
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Tool\LoadTemplate;

use Library\MemoryCache;
use Game\Config\GameConfig;

class Save
{
    use Log;

    protected ?MemoryCache $db;

    protected int $cacheId;

    public function __construct()
    {
        $this->db = MemoryCache::getInstance();
    }

    public function initCache($type): bool
    {
        $this->cacheId = $this->makeCacheId($type);
        if ($this->db->CreateCache($this->cacheId, 8 * 1024 * 1024) == false) {
            $this->db = null;
            return false;
        }
        return true;
    }

    public function delCache($type): bool
    {
        return $this->db->removeCache($this->makeCacheId($type));
    }

    private function makeCacheId($type): int
    {
        return GameConfig::getInstance()->DATA_VERSION()  * 1000 + $type;
    }
    /**
     * @param $context
     * @return bool
     */
    public function updateTable($context): bool
    {
        $jsonKeyList = array_keys($context);
        if ($this->db->SetCache(0, $jsonKeyList, $this->cacheId) == false) {
            $log = $this->db->getLastError();
            $this->addError("save index error cache:" . $this->cacheId . "db error:" . $log);
            return false;
        }
        if ($this->dealDBData($jsonKeyList, $context) == false) {
            return false;
        }
        unset($this->_jsonKeyList);
        return true;
    }

    public function saveData($tplId, &$data, $type = 0): bool
    {
        $cacheId = $this->cacheId;
        if ($type != 0) {
            $cacheId = $this->makeCacheId($type);
        }
        return $this->db->SetCache($tplId, $data, $cacheId);
    }

    public function getData($tplId, $type = 0): ?array
    {
        $cacheId = $this->cacheId;
        if ($type != 0) {
            $cacheId = $this->makeCacheId($type);
        }
        $data = $this->db->GetCache($tplId, $cacheId);
        if ($data === null) {
            $log = $this->db->getLastError();
            $this->addError("get data error cache:" . $this->cacheId . "db error:" . $log);
            return null;
        }
        return $data;
    }

    private function dealDBData(&$jsonKeyList, &$context): bool
    {
        foreach ($jsonKeyList as $tplId) {
            if ($this->saveData($tplId, $context[$tplId]) == false) {
                $log = sprintf(
                    "update Table[%s] Fail Because save db Fail!! cache error:%s ",
                    $this->cacheId,
                    $this->db->getLastError()
                );
                $this->addError($log);
                return false;
            }
        }
        return true;
    }
}
