package com.qxgmat.help;

import com.qxgmat.data.dao.entity.Manager;
import com.qxgmat.data.dao.entity.User;
import com.qxgmat.util.shiro.ManagerRealm;
import com.qxgmat.util.shiro.OauthRealm;
import com.qxgmat.util.shiro.UserRealm;
import com.nuliji.tools.shiro.inter.impl.RealmUsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * Created by GaoJie on 2017/07/31.
 */
@Service
public class ShiroHelp{
    public Subject getSession() {
        return SecurityUtils.getSubject();
    }

    public User getLoginUser() {
        return getLogin(User.class);
    }

    public Manager getLoginManager(){
        return getLogin(Manager.class);
    }

    public RealmUsernamePasswordToken user(String username, String password){
        return new RealmUsernamePasswordToken(username, password, UserRealm.class);
    }
    public RealmUsernamePasswordToken manager(String username, String password){
        return new RealmUsernamePasswordToken(username, password, ManagerRealm.class);
    }
    public RealmUsernamePasswordToken oauth(String code, String platform){
        return new RealmUsernamePasswordToken(code, platform, OauthRealm.class);
    }

    public RealmUsernamePasswordToken user(String username, String password, Boolean remember){
        return new RealmUsernamePasswordToken(username, password, remember == null ? false : remember, UserRealm.class);
    }
    public RealmUsernamePasswordToken manager(String username, String password, Boolean remember){
        return new RealmUsernamePasswordToken(username, password, remember == null ? false : remember, ManagerRealm.class);
    }

    public <T> T getLogin(Class<T> clazz){
        PrincipalCollection pc = SecurityUtils.getSubject().getPrincipals();
        if(pc == null) return null;
        Collection c = pc.byType(clazz);
        return c.size() > 0 ? (T) c.toArray()[0] : null;
    }

    public void logout() {
        Subject subject = getSession();
        subject.logout();
//        RealmSecurityManager sm = (RealmSecurityManager)SecurityUtils.getSecurityManager();
//        Iterator var3 = sm.getRealms().iterator();
//
//        Realm realm;
//        while(var3.hasNext()){
//            realm = (Realm)var3.next();
//        }
    }

    public void refresh(){
        getSession().getSession().touch();
    }
}
