/*
 * Decompiled with CFR 0.152.
 *
 * Could not load the following classes:
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 *  org.springframework.dao.PessimisticLockingFailureException
 *  org.springframework.data.redis.cache.CacheStatistics
 *  org.springframework.data.redis.cache.CacheStatisticsCollector
 *  org.springframework.data.redis.cache.RedisCacheWriter
 *  org.springframework.data.redis.connection.RedisConnection
 *  org.springframework.data.redis.connection.RedisConnectionFactory
 *  org.springframework.data.redis.connection.RedisStringCommands$SetOption
 *  org.springframework.data.redis.core.types.Expiration
 *  org.springframework.lang.Nullable
 *  org.springframework.util.Assert
 */
package org.jeecg.common.modules.redis.writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.data.redis.cache.CacheStatistics;
import org.springframework.data.redis.cache.CacheStatisticsCollector;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

public class JeecgRedisCacheWriter implements RedisCacheWriter {
    private static final Logger log = LoggerFactory.getLogger(JeecgRedisCacheWriter.class);
    private final RedisConnectionFactory connectionFactory;
    private final Duration sleepTime;
    private final CacheStatisticsCollector statistics = CacheStatisticsCollector.create();

    public JeecgRedisCacheWriter(RedisConnectionFactory connectionFactory) {
        this(connectionFactory, Duration.ZERO);
    }

    public JeecgRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
        Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
        Assert.notNull(sleepTime, "SleepTime must not be null!");
        this.connectionFactory = connectionFactory;
        this.sleepTime = sleepTime;
    }

    public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        Assert.notNull(value, "Value must not be null!");
        this.execute(name, connection -> {
            if (JeecgRedisCacheWriter.shouldExpireWithin(ttl)) {
                connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
            } else {
                connection.set(key, value);
            }
            return "OK";
        });
    }

    public byte[] get(String name, byte[] key) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        return this.execute(name, connection -> connection.get(key));
    }

    public byte[] putIfAbsent(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        Assert.notNull(value, "Value must not be null!");
        return (byte[]) this.execute(name, connection -> {
            Object var7;
            if (this.isLockingCacheWriter()) {
                this.doLock(name, connection);
            }
            try {
                boolean put = JeecgRedisCacheWriter.shouldExpireWithin(ttl) ? connection.set(key, value, Expiration.from(ttl), RedisStringCommands.SetOption.ifAbsent()).booleanValue() : connection.setNX(key, value).booleanValue();
                if (!put) {
                    byte[] var11;
                    byte[] byArray = var11 = connection.get(key);
                    return byArray;
                }
                var7 = null;
            } finally {
                if (this.isLockingCacheWriter()) {
                    this.doUnlock(name, connection);
                }
            }
            return var7;
        });
    }

    public void remove(String name, byte[] key) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        String keyString = new String(key);
        log.info("redis remove key:" + keyString);
        String keyIsAll = "*";
        if (keyString.endsWith(keyIsAll)) {
            this.execute(name, connection -> {
                Set keys = connection.keys(key);
                int delNum = 0;
                for (Object keyByte : keys) {
                    delNum = (int) ((long) delNum + connection.del(new byte[][]{(byte[]) keyByte}));
                }
                return delNum;
            });
        } else {
            this.execute(name, connection -> connection.del(new byte[][]{key}));
        }
    }

    public void clean(String name, byte[] pattern) {
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(pattern, "Pattern must not be null!");
        this.execute(name, connection -> {
            boolean wasLocked = false;
            try {
                byte[][] keys;
                if (this.isLockingCacheWriter()) {
                    this.doLock(name, connection);
                    wasLocked = true;
                }
                if ((keys = Optional.ofNullable(connection.keys(pattern)).orElse(Collections.emptySet()).toArray(new byte[0][0])).length > 0) {
                    connection.del(keys);
                }
            } finally {
                if (wasLocked && this.isLockingCacheWriter()) {
                    this.doUnlock(name, connection);
                }
            }
            return "OK";
        });
    }

    void lock(String name) {
        this.execute(name, connection -> this.doLock(name, connection));
    }

    void unlock(String name) {
        this.executeLockFree(connection -> this.doUnlock(name, connection));
    }

    private Boolean doLock(String name, RedisConnection connection) {
        return connection.setNX(JeecgRedisCacheWriter.createCacheLockKey(name), new byte[0]);
    }

    private Long doUnlock(String name, RedisConnection connection) {
        return connection.del(new byte[][]{JeecgRedisCacheWriter.createCacheLockKey(name)});
    }

    boolean doCheckLock(String name, RedisConnection connection) {
        return Boolean.TRUE.equals(connection.exists(JeecgRedisCacheWriter.createCacheLockKey(name)));
    }

    private boolean isLockingCacheWriter() {
        return !this.sleepTime.isZero() && !this.sleepTime.isNegative();
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private <T> T execute(String name, Function<RedisConnection, T> callback) {
        try (RedisConnection connection = this.connectionFactory.getConnection();) {
            this.checkAndPotentiallyWaitUntilUnlocked(name, connection);
            T t = callback.apply(connection);
            return t;
        }
    }

    private void executeLockFree(Consumer<RedisConnection> callback) {
        try (RedisConnection connection = this.connectionFactory.getConnection();) {
            callback.accept(connection);
        }
    }

    private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {
        if (this.isLockingCacheWriter()) {
            try {
                while (this.doCheckLock(name, connection)) {
                    Thread.sleep(this.sleepTime.toMillis());
                }
            } catch (InterruptedException var4) {
                Thread.currentThread().interrupt();
                throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name), var4);
            }
        }
    }

    private static boolean shouldExpireWithin(@Nullable Duration ttl) {
        return ttl != null && !ttl.isZero() && !ttl.isNegative();
    }

    private static byte[] createCacheLockKey(String name) {
        return (name + "~lock").getBytes(StandardCharsets.UTF_8);
    }

    public CacheStatistics getCacheStatistics(String cacheName) {
        return this.statistics.getCacheStatistics(cacheName);
    }

    public void clearStatistics(String name) {
    }

    public RedisCacheWriter withStatisticsCollector(CacheStatisticsCollector cacheStatisticsCollector) {
        return null;
    }
}