<?php

namespace app\common\token\driver;

use think\facade\Config;
use think\Response;
use BadFunctionCallException;
use app\common\token\Driver;
use think\exception\HttpResponseException;

/**
 * @see Driver
 */
class Redis extends Driver
{
    /**
     * 默认配置
     * @var array
     */
    protected $options = [];

    /**
     * 构造函数
     * @access public
     * @param array $options 参数
     */
    public function __construct(array $options = [])
    {
        if (!extension_loaded('redis')) {
            throw new BadFunctionCallException('未安装redis扩展');
        }
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $this->handler = new \Redis;
        if ($this->options['persistent']) {
            $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
        } else {
            $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
        }

        if ('' != $this->options['password']) {
            $this->handler->auth($this->options['password']);
        }

        if (false !== $this->options['select']) {
            $this->handler->select($this->options['select']);
        }
    }

    public function set(string $token, string $type, array $userinfo, int $expire = null): bool
    {
        if (is_null($expire)) {
            $expire = $this->options['expire'];
        }
        $data =json_encode($userinfo,JSON_UNESCAPED_UNICODE);
        $result = $this->handler->set($type.":info:".$token,$data,$expire);
        return $result;
    }

    public function get(string $token, bool $expirationException = true): array
    {
        $data = $this->handler->get($token);
        if (is_null($data) || false === $data) {
            return [];
        }
        $this->handler->set($token, $data, $this->options['expire']);
        // 返回未加密的token给客户端使用
        return json_decode($data,true);
    }

    public function check(string $token, string $type, array $userinfo, bool $expirationException = true): bool
    {
        $data = $this->get($token, $expirationException);
        if (!$data || (!$expirationException && $data['expiretime'] && $data['expiretime'] <= time())) return false;
        return $data['type'] == $type && $data['user_id'] == $userinfo['id'];
    }

    public function delete(string $token): bool
    {
        $data = $this->get($token, false);
        if ($data) {
            $key     = $this->getEncryptedToken($token);
            $user_id = $data['user_id'];
            $this->handler->del($key);
            $this->handler->sRem($this->getUserKey($user_id), $key);
        }
        return true;
    }

    public function clear(string $type, int $user_id): bool
    {
        $keys = $this->handler->sMembers($this->getUserKey($user_id));
        $this->handler->del($this->getUserKey($user_id));
        $this->handler->del($keys);
        return true;
    }

    /**
     * 获取会员的key
     * @param $user_id
     * @return string
     */
    protected function getUserKey($user_id): string
    {
        return $this->options['userprefix'] . $user_id;
    }

}