package com.diagbot.facade;

import com.diagbot.dto.RespDTO;
import com.diagbot.entity.Permission;
import com.diagbot.entity.User;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.PermissionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description: 资源
 * @Author: ztg
 * @Date: 2018/9/17 18:32
 */
@Component
public class PermissionFacade extends PermissionServiceImpl {

    @Autowired
    UserFacade userFacade;

    /**
     * @Description: 获取资源信息
     * @Author: ztg
     * @Date: 2018/9/25 15:10
     */
    public RespDTO getPermission(String appkey, String secret) {
        User user = userFacade.findByName(appkey);
        if(null == user){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "未找到对应的appkey【" + appkey + "】" );
        }
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        if(!passwordEncoder.matches(secret, user.getPassword())){
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "appkey 或 secret 错误！【" + appkey + "," + secret + "】");
        }
        List<Permission> permissions = this.getPermissionByUserId(user.getId());
        return RespDTO.onSuc(permissions);
    }
   

}
