package ink.wgink.gateway.handler.sign;

import ink.wgink.gateway.consts.ISystemConst;
import ink.wgink.gateway.exception.SignException;
import ink.wgink.gateway.handler.BaseHandler;
import ink.wgink.gateway.pojo.result.SuccessResult;
import ink.wgink.gateway.pojo.sign.In;
import ink.wgink.gateway.pojo.user.User;
import ink.wgink.gateway.util.RequestFieldCheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: SignHandler
 * @Description: 登录登出
 * @Author: wanggeng
 * @Date: 2021/4/23 12:30 下午
 * @Version: 1.0
 */
@Service
public class SignHandler extends BaseHandler {

    public Mono<ServerResponse> in(ServerRequest serverRequest) {
        Mono<In> inMono = serverRequest.bodyToMono(In.class);
        return inMono.flatMap(in -> {
            RequestFieldCheckUtil.check(in);
            if (!StringUtils.equals(in.getUsername(), ISystemConst.USER_ADMIN_USERNAME)) {
                return Mono.error(new SignException("用户名错误"));
            }
            if (!StringUtils.equals(in.getPassword(), ISystemConst.USER_ADMIN_PASSWORD)) {
                return Mono.error(new SignException("密码错误"));
            }
            return serverRequest.session().flatMap(webSession -> {
                User user = new User();
                user.setUuid("1");
                user.setUsername(ISystemConst.USER_ADMIN_USERNAME);
                user.setPassword(ISystemConst.USER_ADMIN_PASSWORD);
                webSession.getAttributes().put(ISystemConst.SESSION_USER, user);
                return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(Mono.just(new SuccessResult()), SuccessResult.class);
            });
        });
    }

    public Mono<ServerResponse> out(ServerRequest serverRequest) {
        return serverRequest.session().flatMap(webSession -> {
            webSession.getAttributes().remove(ISystemConst.SESSION_USER);
            return ServerResponse.temporaryRedirect(URI.create(ISystemConst.PAGE_LOGIN)).build();
        });
    }

}
