<?php

namespace APP\program\admin;

use APP\DI;
use APP\program\system\System;
use Exception;
use LyApi\tools\Config;
use Predis\Connection\ConnectionException;

/**
 * LyApi - Admin System
 * 用于Admin缓存操作
 */

class Cache
{

    private $setting;

    public function __construct($cache, $option)
    {
        $this->setting = Config::getConfig("develop", 'admin', 'json');
    }

    // 当前缓存类型
    public static function cahceType()
    {
        return Config::getConfig("develop", 'admin', 'json')['cache-system'];
    }

    public static function cleanFileCahce()
    {
        $config = Config::getConfig("develop", 'admin', 'json');
        $allFile = Apis::allTree(LyApi . '/data/cache/' . $config['cache-setting']['file']['rpath'], $config['cache-setting']['file']['forbid-clean']);
        foreach ($allFile as $key => $value) {
            if(array_key_exists('path',$value)){
                unlink($value['path'] . '/' . $value['title']);
            }else{
                System::deldir(LyApi . '/data/cache/' . $config['cache-setting']['file']['rpath'] . '/' . $value['title']);
            }
        }
    }

    public static function cacheTime(){
        $db_connect = Setting::dbConnect();
        return $db_connect->get('admin_setting','context',[
            'comment' => 'site_cache_time'
        ]);
    }

    public static function cacheObject($group = '', $minfo = false)
    {
        $ctype = self::cahceType();
        $setting = Config::getConfig("develop", 'admin', 'json');
        $object = false;
        if ($ctype == 'file') {
            $object = DI::FileCache($setting['cache-setting']['file']['rpath'] . '/' . $group);
        } else if ($ctype == 'redis') {
            $object = DI::RedisCache($setting['cache-setting']['redis']);

            try {
                $object->get('test');
            } catch (Exception $e) {
                if(true){
                    $ctype = 'file';
                    $object = DI::FileCache($setting['cache-setting']['file']['rpath'] . '/' . $group);
                }
            }

        }else{
            $object = false;
        }

        if ($minfo) {
            return [$object, $ctype];
        } else {
            return $object;
        }

    }
}
