package com.qxgmat.util.shiro;

import com.qxgmat.data.dao.entity.Manager;
import com.qxgmat.data.dao.entity.ManagerRole;
import com.qxgmat.service.inline.ManagerRoleService;
import com.qxgmat.service.ManagerService;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

/**
 * Created by GaoJie on 2017/11/3.
 */
public class ManagerRealm extends AuthorizingRealm {
    private static final FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    private static final Logger logger = LoggerFactory.getLogger(ManagerRealm.class);

    @Autowired
    private ManagerService managerService;

    @Autowired
    private ManagerRoleService managerRoleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        logger.debug("{}", principalCollection.getRealmNames());
        String className = ManagerRealm.class.getName();
        boolean selected = false;
        for(String realmNames: principalCollection.getRealmNames()){
            if(realmNames.contains(className)) selected = true;
        }
        if(!selected) return null;
        Manager manager = (Manager)principalCollection.getPrimaryPrincipal();
        ManagerRole role = managerRoleService.get(manager.getRoleId());

        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        ArrayList<String> roleAuthorization = new ArrayList<String>();
        roleAuthorization.add("manager");

//        logger.debug("{}", roleAuthorization);
        sa.addRoles(roleAuthorization);

        if (role != null){
            String[] permissionList = role.getPermissionList();
            if (permissionList.length > 0){
                sa.addStringPermissions(Arrays.asList(permissionList));
            }
        }
        return sa;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            throw new UnknownAccountException("用户名或密码不能为空！");
        }
        Manager manager = managerService.getByUserName(username);
        if (manager == null || manager.getId() <= 0) {
            throw new UnknownAccountException("用户不存在！");
        }
        if(!managerService.equalsPassword(manager, password)){
            throw new IncorrectCredentialsException("用户名或密码错误！");
        }
        return new SimpleAuthenticationInfo(manager, password, getName());
    }
}
