/**
 * <p>Copyright:Copyright(c) 2016</p>
 * <p>Company:上海中信信息发展股份有限公司</p>
 * <p>类更新历史信息</p>
 * @author huz
 * @date 2016-09-19 14:58
 * @todo
 */

package com.cesgroup.cesmonitor.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.shiro.util.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cesgroup.framework.commons.SpringContextUtils;
import com.zabbix4j.ZabbixApi;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.user.UserLoginResponse2;

/**
 * 认证服务
 *
 * @author zhang.erwei
 * @version 1.0.0 2017年5月24日
 */
@Service("identityService")
public class IdentityService {

    // 依赖注入开始
    @Value("${zabbix.url}")
    private String url;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public static String LOGIN_USER = "LoginUser";

    private Map<String, LoginUser> loginUsers = new ConcurrentHashMap<String, LoginUser>();

    //菜单打开
    @Value("${key.Private}")
    private String Key;

    public String getKey() {
        return Key;
    }

    public void setKey(final String Key) {
        this.Key = Key;
    }

    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public LoginUser getLoginUser() {
        // HttpServletRequest request =
        // ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            String username = (String) ThreadContext.get(IdentityService.LOGIN_USER);
            if (username == null) {
                username = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal();
            }
            // WebApplicationContext
            // context=org.springframework.web.servlet.support.RequestContextUtils.getWebApplicationContext(request);
            // return context.getBean("identityService",
            // IdentityService.class).getLoginUser(username);
            LoginUser user = SpringContextUtils.getBean(IdentityService.class).getLoginUser(username);
            //System.out.println(Util.toJSON(user));
            return user;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param username
     *            用户名
     * @return
     *         用户
     */
    public LoginUser getLoginUser(final String username) {
        if (username == null) {
            return null;
        }
        return loginUsers.get(username);
    }

    /**
     * 登录
     *
     * @param username
     *            用户名
     * @param password
     *            密码
     * @return 登录用户
     */
    public LoginUser login(final String username, final String password) {
        try {
            ZabbixApi zabbixApi = new ZabbixApi(url);
            LoginUser user = new LoginUser();
            // user.setName(username);
            user.setPassword(password);
            user.setUsername(username);
            UserLoginResponse2 response = zabbixApi.login2(username, password);
            user.setZabbixApi(zabbixApi);
            loginUsers.put(username, user);
            user.setType(response.getResult().getType());
            user.setTheme(response.getResult().getTheme());
            user.setLang(response.getResult().getLang());
            user.setUserid(response.getResult().getUserid());
            user.setSurname(response.getResult().getSurname());
            user.setName(response.getResult().getName());
            ThreadContext.put(IdentityService.LOGIN_USER, username);
            return user;
        } catch (ZabbixApiException e) {
            //Account is blocked for %s seconds
            //System.out.println(e.getMessage());
            logger.warn(e.getMessage());
            if (e.getMessage() != null && e.getMessage().contains("blocked")) {
                throw new RuntimeException("登录失败超过5次，账号被锁定，5分钟后重试！", e);
            } else {
                throw new RuntimeException("用户名或密码不正确", e);
            }
        }

    }

}
