package com.qmth.sop.server.auth;

import com.qmth.boot.core.security.model.AccessEntity;
import com.qmth.boot.tools.signature.SignatureType;
import com.qmth.sop.business.cache.CommonCacheService;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBSession;
import com.qmth.sop.common.contant.SpringContextHolder;
import com.qmth.sop.common.enums.ExceptionResultEnum;

import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;

public class SopServerSession implements AccessEntity {

    private String identity;

    private SignatureType signatureType;

    public SopServerSession(String identity, SignatureType signatureType) {
        this.identity = identity;
        this.signatureType = signatureType;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    @Override
    public String getIdentity() {
        return identity;
    }

    @Override
    public String getSecret() {
        CommonCacheService commonCacheService = SpringContextHolder.getBean(CommonCacheService.class);
        TBSession tbSession = (TBSession) commonCacheService.getUserSession(identity);
        Optional.ofNullable(tbSession).orElseThrow(() -> ExceptionResultEnum.NOT_LOGIN.exception());
        return tbSession.getAccessToken();
    }

    @Override
    public Collection<String> getAllowIP() {
        return null;
    }

    @Override
    public Collection<String> getDenyIP() {
        return null;
    }

    public SignatureType getSignatureType() {
        return signatureType;
    }

    public void setSignatureType(SignatureType signatureType) {
        this.signatureType = signatureType;
    }

    @Override
    public String getLogName() {
        CommonCacheService commonCacheService = SpringContextHolder.getBean(CommonCacheService.class);
        TBSession tbSession = (TBSession) commonCacheService.getUserSession(identity);
        StringJoiner stringJoiner = new StringJoiner("_");
        if (Objects.nonNull(tbSession)) {
            if (Objects.nonNull(tbSession.getIdentity())) {
                SysUser sysUser = commonCacheService.userCache(Long.parseLong(tbSession.getIdentity()));
                stringJoiner.add("{" + sysUser.getLoginName() + "}").add("{" + tbSession.getType() + "}");
            }
        }
        return stringJoiner.toString();
    }
}
