package com.wyz.demo.controller;


import com.wyz.demo.dto.UserDTO;
import com.wyz.demo.service.UserService;
import com.wyz.demo.vo.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public UserService userService;

    @GetMapping("/hello")
    public String simpleString(){
        return "<h2>/hello</h2><br>";
    }




    /**
     * 用户注册
     *
     * 情况1: 用户名已经被注册了
     * 情况2: 正常注册
     *
     * @return
     */
    @PostMapping(value = "/register")
    public Message register(@RequestBody UserDTO u, HttpServletResponse resp, HttpSession sess){
        log.info("this is userDTO: {}",u);
        Message msg = userService.addUser(u,resp,sess);
        return msg;
    }



    /**
     * 用户登录: 需要返回
     *
     * 情况1: 用户名不存在
     * 情况2: 用户名存在, 但是密码错误
     * 情况3: 正确登录, 并注册一个session
     *
     * @param u
     */
    @PostMapping(value = "/login")
    public Message login(@RequestBody UserDTO u, HttpServletResponse resp, HttpSession sess){

        log.info("请求登录的-userDTO: {}",u);
        Message msg = userService.checkUser(u, resp, sess);
        return msg;

    }

    /**
     * 添加用户: 前端发个请求看看用户是否登录
     *
     * 情况1: 没有登录
     * 情况2: 已经登录
     *
     * @return
     */
    @RequestMapping(value = "/check")
    public Message check(HttpSession sess){
        Message msg = userService.checkStatus(sess);
        return msg;
    }


    /**
     * 添加用户: 前端发个请求注销
     *
     * 情况1:
     *
     * @return
     */
    @RequestMapping(value = "/logout")
    public void logout(HttpSession sess){
        log.info("用户:{} 已经注销",sess.getAttribute("username"));
        sess.invalidate();
    }


}
