package com.palmnest.webapp.filter;

import com.palmnest.application.Constants;
import com.palmnest.model.User;
import com.palmnest.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author linjinyu
 * @Description Superdesk app backend login
 * @date 2019/8/9 10:19
 **/

@Component
public class SpuerdeskAppAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private UserManager userManager;

	/**
	 * 认证方法 ---- 自定义
	 *
	 * @param authentication
	 * @return
	 * @throws AuthenticationException
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		// username
		String username = authentication.getName();

		System.out.println("authentication.getName() = [" + username + "]");

		// password TODO 改jwt
		String password = authentication.getCredentials().toString();

		System.out.println("authentication.getCredentials().toString() = [" + password + "]");

		// example https://externaluser:pass@wx.palmnest.com/super_service/admin/dorm/jumpDormitoryInfor?funcid=252

		if ("externaluser".equals(username) && "pass".equals(password)) {

			// 权限 写死 给 最高 TODO
			List<GrantedAuthority> roleList = new ArrayList<GrantedAuthority>();

			GrantedAuthority authorityAdmin = new SimpleGrantedAuthority(Constants.ADMIN_ROLE);
			GrantedAuthority authorityUser  = new SimpleGrantedAuthority(Constants.USER_ROLE);

			roleList.add(authorityAdmin);
			roleList.add(authorityUser);

			// 用户 写死 给 admin TODO
			User user = userManager.getUserByUsername2("admin");

			// TODO 只是伪造 这两个是不行的


			// 外部系统 single login use
//            "PcToken" -> "1A2DE21C961BD83CA7982602020D9E71756BA517F126A789"
//            "javax.servlet.jsp.jstl.fmt.request.charset" -> "UTF-8"

			// /mnt1t/JAVA_HOME/super_service/src/main/java/com/palmnest/webapp/controller/AdminAjaxController.java
			// loadMenuTree
			//用户Sesson缓存
//            request.getSession().setAttribute("FunctionOperateCache", funcOperateCache);r55r
//            request.getSession().setAttribute("UserPerms", perms);//用户权限
//            request.getSession().setAttribute("UserCache", user);
//            // request.getSession().setAttribute("UserOrgRelationsCache", userManager.getUserOrgByUserId(user.getId().longValue()));
//            request.getSession().setAttribute("orgs", appUserService.getUserOrgs(user.getId()));

//            "FunctionOperateCache" -> " size = 159"
//            "orgs" -> " size = 527"
//            "UserPerms" -> "pc:system,pc:system:user,pc:system:role,pc:system:menu,pc:system:function,pc:basics:dictionary,pc:setting:wechat,pc:organization,pc:organization:project,pc:organization:build,pc:organization:company,pc:organization:dept,pc:setting,pc:setting:service,pc:setting:project,pc:organization:enterprise-data,pc:basics,pc:organization:floor,pc:consume:template,pc:consume:push,pc:consume:history,pc:consume,pc:notice,pc:notice:publish,pc:notice:list,pc:basics:wxtemplate,pc:basics:email,pc:repair,pc:repair:launch,pc:repair:evaluate,pc:repair:list,pc:enter:list,pc:enter:config,pc:enter,pc:emigration,pc:emigration:list,pc:emigration:config,pc:release:history,pc:release:approval,pc:release,pc:repair:list:approve,pc:setting:custom,pc:washcar,pc:washcar:list,pc:setting:module,pc:organization:enterprise-account,pc:enter:list:approve,pc:emigration:list:approve,pc:notice:list:approve,pc:basics:sms,pc:dormitory:config,pc:dormitory:dormlist,pc:dormitory:checkout,pc:dormitory,pc:basics:tradearea,pc:dinner,pc:dinne"
//            "UserCache" ->
//            "SPRING_SECURITY_CONTEXT" -> "org.springframework.security.core.context.SecurityContextImpl@28904d56: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@28904d56: Principal: com.palmnest.model.User@6c8d4f66; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 130vadno25zo31dfgf6ghhmz92; Granted Authorities: ROLE_USER"

			return new UsernamePasswordAuthenticationToken(user, password, /*Collections.emptyList()*/ roleList);

		} else {

			throw new BadCredentialsException("External system authentication failed");
		}

	}

	@Override
	public boolean supports(Class<?> authentication) {

		return authentication.equals(UsernamePasswordAuthenticationToken.class);

	}
}