package com.yihu.hos.tenant.service;

import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.tenant.model.TenantModel;
import com.yihu.hos.tenant.model.TenantSession;
import com.yihu.hos.system.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @created Airhead 2016/11/16.
 */
@Service
public class AuthenticateService {
    @Autowired
    private UserDao userDao;

    @Resource(name = TenantService.BEAN_ID)
    private TenantService tenantService;

    public boolean isAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        TenantSession tenantSession = (TenantSession) session.getAttribute(ContextAttributes.TENANT_SESSION);
        if (tenantSession == null) {
            return false;
        }

        LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA, tenantSession.getSchema());
        return true;
    }

    /**
     *  //TODO 需要进一步完善逻辑
     *  租户登录授权
     * @param httpSession
     * @param tenantName
     * @return
     * @throws Exception
     */
    public boolean auth(HttpSession httpSession, String tenantName) throws Exception {
        //授权租户，切换到指定数据库，需要先清除原先的数据库指定，切回global_db表，获取租户信息
        LocalContext.getContext().removeAttachment(ContextAttributes.SCHEMA);
        TenantModel tenantModel = tenantService.findTenantByName(tenantName);
        //TODO:现在只是简单逻辑，需要修改成安全逻辑
        if (tenantModel == null ) {
            return false;
        }
        //切换Schema到对应租户
        LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA, tenantModel.getSchema());
        LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA_TEMP, tenantModel.getSchema());
//        UserModel userModel = userDao.findOne(user);
//        //TODO:现在只是简单逻辑，需要修改成安全逻辑
//        if (userModel == null || !password.equals(userModel.getPassword())) {
//            return "User Auth Failed";
//        }
        LocalContext.getContext().setAttachment(ContextAttributes.TENANT_NAME,tenantModel.getName());
        httpSession.setAttribute(ContextAttributes.TENANT_SESSION, new TenantSession(tenantModel.getName(), tenantModel.getSchema()));
        return true;
    }

    /**
     * 登出 - 移除租户授权信息
     * @param httpSession
     * @return
     * @throws Exception
     */
    public String logout(HttpSession httpSession) throws Exception {
        //移除Schema及缓存
        LocalContext.getContext().removeAttachment(ContextAttributes.SCHEMA);
        LocalContext.getContext().removeAttachment(ContextAttributes.SCHEMA_TEMP);
        httpSession.removeAttribute(ContextAttributes.TENANT_SESSION);
        return "Tenan Logout Success";
    }

}
