package com.bootdo.system.service.impl;

import com.bootdo.common.constant.Constants;
import com.bootdo.common.utils.IPUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserOnline;
import com.bootdo.system.service.SessionService;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.bootdo.common.utils.RedisUtil;
import org.springframework.util.ObjectUtils;

/**
 * 待完善
 *
 * @author bootdo
 */
@Service
public class SessionServiceImpl implements SessionService {
    private static final Logger log = LoggerFactory.getLogger(SessionServiceImpl.class);
    private final SessionDAO sessionDAO;

    @Value("${api-allow-ip}")
    private String apiAllowIp;
    @Resource
    private RedisUtil redisUtil;

    @Autowired
    public SessionServiceImpl(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    @Override
    public List<UserOnline> list(HttpServletRequest request) throws Exception{
        String ip = IPUtils.getIpAddr(request);
        log.info("SessionServiceImpl.list.ip:" + ip);
        if (!apiAllowIp.contains(ip)) {
            throw new Exception("不允许访问");
        }
        List<UserOnline> list = new ArrayList<>();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            UserOnline userOnline = new UserOnline();
            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
                continue;
            } else {
                SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session
                        .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                UserDO userDO = (UserDO) principalCollection.getPrimaryPrincipal();
                userOnline.setUsername(userDO.getUsername());
            }
            userOnline.setId((String) session.getId());
            userOnline.setHost(session.getHost());
            userOnline.setStartTimestamp(session.getStartTimestamp());
            userOnline.setLastAccessTime(session.getLastAccessTime());
            userOnline.setTimeout(session.getTimeout() / (1000L * 60L));
            list.add(userOnline);
        }
        return list;
    }

    @Override
    public List<UserDO> listOnlineUser() {
        List<UserDO> list = new ArrayList<>();
        UserDO userDO;
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
                continue;
            } else {
                principalCollection = (SimplePrincipalCollection) session
                        .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                userDO = (UserDO) principalCollection.getPrimaryPrincipal();
                list.add(userDO);
            }
        }
        return list;
    }

    @Override
    public boolean logout() throws Exception {

        //删除登录的用户
        redisUtil.hdel(Constants.ONLINE_USER, ShiroUtils.getUser().getUsername());
        ShiroUtils.logout();
        return true;
    }

    @Override
    public Collection<Session> sessionList() {
        return sessionDAO.getActiveSessions();
    }

    @Override
    public boolean forceLogout(String sessionId,HttpServletRequest request) throws Exception {
        String ip = IPUtils.getIpAddr(request);
        log.info("SessionServiceImpl.forceLogout.ip:"+ ip);
        if (!apiAllowIp.contains(ip)) {
            throw new Exception("不允许访问");
        }

        Session session = sessionDAO.readSession(sessionId);

        if(!ObjectUtils.isEmpty(session)){
            SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session
                    .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            UserDO userDO = (UserDO) principalCollection.getPrimaryPrincipal();
            //删除登录的用户
            redisUtil.hdel(Constants.ONLINE_USER, userDO.getUsername());

            session.stop();

            sessionDAO.delete(session);
        }

        return true;
    }




}
