package com.passionProject.bikeProject.Controller;

import com.passionProject.bikeProject.Entity.User;
import com.passionProject.bikeProject.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin(origins = "http://localhost:8080")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody User newUser) {
        HttpStatus httpStatus = HttpStatus.CONFLICT;
        User user = null;
        if (userService.find(newUser.getUsername()) == null) {
            user = userService.save(newUser);
            httpStatus = HttpStatus.CREATED;
        }
        return new ResponseEntity<>(user, new HttpHeaders(), httpStatus);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseEntity<?> loginUser(@RequestBody User user) {
        HttpStatus httpStatus = HttpStatus.UNPROCESSABLE_ENTITY;
        HttpHeaders httpHeaders = new HttpHeaders();
        User foundUser = userService.find(user.getUsername());
        if (foundUser != null) {
            if (foundUser.getPassword().equals(user.getPassword())) httpStatus = HttpStatus.ACCEPTED;
        }
        return new ResponseEntity<>(foundUser, httpHeaders, httpStatus);
    }

    @RequestMapping(value = "/getUsers", method = RequestMethod.GET)
    public ResponseEntity<?> getUsers() {
        HttpStatus httpStatus = HttpStatus.OK;
        HttpHeaders httpHeaders = new HttpHeaders();
        Iterable<User> users = userService.getAllUsers();
        return new ResponseEntity<>(users, httpHeaders, httpStatus);
    }
}
