package org.holer.server.rest;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.holer.server.constant.HolerCode;
import org.holer.server.db.DBUserService;
import org.holer.server.model.HolerResult;
import org.holer.server.model.HolerUser;
import org.holer.server.util.ServerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@CrossOrigin
@RestController
@RequestMapping({"/user"})
public class RESTUserService {
    @Autowired
    private DBUserService userService;

    @PostMapping({"/login"})
    public HolerResult<?> login(@RequestBody HolerUser user, HttpSession session) {
        String passwd = user.getPassword();
        HolerUser dbUser = this.userService.findByNameAndPassword(user.getName(), passwd);
        if (null == dbUser) {
            return ServerUtil.failure(HolerCode.BAD_USER);
        }

        String token = ServerUtil.randomID();
        session.setAttribute("NOSUM-AUTH-TOKEN", token);

        dbUser.setToken(token);
        this.userService.save(dbUser);

        dbUser.setPassword(null);
        return ServerUtil.success(dbUser);
    }


    @GetMapping({"/logout"})
    public HolerResult<?> logout(HttpSession session) {
        String token = (String) session.getAttribute("NOSUM-AUTH-TOKEN");
        session.removeAttribute("NOSUM-AUTH-TOKEN");
        session.invalidate();

        if (StringUtils.isBlank(token)) {
            return ServerUtil.failure(HolerCode.BAD_TOKEN);
        }


        HolerUser dbUser = this.userService.findByToken(token);
        if (null == dbUser) {
            return ServerUtil.failure(HolerCode.BAD_TOKEN);
        }

        dbUser.setToken(null);
        this.userService.save(dbUser);
        return ServerUtil.success(dbUser.getUserId());
    }
}
