package me.chyxion.tigon.shiro.cache.shiro;

import java.util.Set;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.springframework.util.Assert;
import org.apache.shiro.session.Session;
import org.springframework.data.redis.core.*;
import org.apache.shiro.cache.CacheException;
import me.chyxion.tigon.shiro.model.AuthUser;
import me.chyxion.tigon.shiro.cache.SessionCache;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * You may find session by user id
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * May 12, 2016 1:25:02 PM
 */
@Slf4j
public class UserIdKeyRedisSessionCache implements SessionCache {

    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTpl;
    @Value("${shiro.session.redis.prefix:AUTH_SESSION}")
    protected String prefix;
    protected String userIdSessionPrefix;

    /**
     * init
     */
    @PostConstruct
    void init() {
        userIdSessionPrefix = prefix + ":USER";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session get(Serializable sessionId) {
        log.info("Redis Session Cache Get [{}].", sessionId);
        Session session = (Session) valueOp().get(prefix + ":" + sessionId);
        log.debug("Session [{}] Found.", session);
        return session;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session put(Session session) {
        return put(session.getId(), session);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session put(Serializable sessionId, Session session) {
        log.info("Redis Session Cache Put [{}:{}:{}].", prefix, sessionId, session);
        valueOp().set(prefix + ":" + sessionId,
            (Serializable) session,
            session.getTimeout(),
            TimeUnit.MILLISECONDS);
        return session;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session remove(Serializable sessionId) {
        log.info("Redis Session Cache Remove [{}].", sessionId);
        Session session = get(sessionId);
        if (session != null) {
            log.info("Redis Session Cache Remove [{}].", session);
            redisTpl.delete(prefix + ":" + sessionId);
        }
        return session;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void clear() throws CacheException {
        log.warn("Redis Session Cache #clear Not Supported");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int size() {
        Long size = hashOp().size(userIdSessionPrefix);
        return size != null ? size.intValue() : 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Set<Serializable> keys() {
        log.warn("Redis Session Cache #keys Not Supported");
        return Collections.emptySet();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<Session> values() {
        log.warn("Redis Session Cache #values Not Supported");
        return Collections.emptyList();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session findByUserId(final Serializable userId) {
        log.debug("Find Session By User Id [{}].", userId);
        Serializable sessionId = hashOp().get(userIdSessionPrefix, userId);
        Session session = null;
        if (sessionId != null) {
            log.debug("User [{}] Session Id [{}] Found.", userId, sessionId);
            session = get(sessionId);
            log.info("User [{}] Session [{}] Found.", userId, session);
            if (session == null) {
                log.info("No User [{}] Session Found, Remove.");
                hashOp().delete(userIdSessionPrefix, userId);
            }
        }
        return session;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session putUserSession(Session session) {
        log.info("Put User Session [{}].", session);
        AuthUser<?> authUser = AuthUser.get(session);
        Assert.state(authUser != null, "Auth User Not Found In Session");
        final Serializable userId = authUser.getUserId();
        Assert.state(userId != null, "Session Auth User Id Could Not Be Null");
        log.info("Put User [{}] Session [{}].", userId, session);
        hashOp().put(userIdSessionPrefix, userId, session.getId());
        return session;
    }

    // --
    // private methods
    protected HashOperations<Serializable, Serializable, Serializable> hashOp() {
        return redisTpl.<Serializable, Serializable>opsForHash();
    }

    protected ValueOperations<Serializable, Serializable> valueOp() {
        return redisTpl.opsForValue();
    }
}
