# -*- coding: utf-8 -*-

__author__ = 'wanger'
__date__ = '2024-08-20'
__copyright__ = '(C) 2024 by siwei'
__revision__ = '1.0'

import time
from typing import Optional
import os
import uuid
import redis
import socket
import config


class Redis:
    redis_client = None
    expire = 60 * 30  # 默认时长   单位s
    hostname = socket.gethostname()
    ipaddress = socket.gethostbyname(hostname)

    # 全局参数修改
    redis_config = config.CONFIG['redis']

    def __init__(
            self,
            host: Optional[str] = redis_config['host'],
            port: Optional[int] = redis_config['port'],
            db: Optional[int] = redis_config['db'],
    ):
        self.redis_client = redis.Redis(host=host, port=port, db=db)

    def set(self, key, value, expire=60 * 30):
        self.redis_client.set(key, value, expire)

    def get(self, key):
        return self.redis_client.get(key)

    def close(self):
        self.redis_client.close()

    def setUsername(self, value, expire=60 * 30):
        self.redis_client.set(self.ipaddress, value, expire)

    def getUsername(self):
        self.redis_client.get(self.ipaddress)

    def get_ip_address(self):
        try:
            # 获取本地主机名
            hostname = socket.gethostname()
            # 获取本地IP
            ip_address = socket.gethostbyname(hostname)
            return ip_address
        except socket.error as e:
            print(f"Unable to get IP Address: {e}")
