package com.ufund.api.ufundapi.controller;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.ufund.api.ufundapi.persistence.UserAuthDAO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.ufund.api.ufundapi.model.User;
import com.ufund.api.ufundapi.persistence.UserDAO;

@RestController
@RequestMapping("users")
public class UserController {
    private static final Logger LOG = Logger.getLogger(UserController.class.getName());
    private final UserDAO UserDAO;
    private final UserAuthDAO userAuthDAO;

    /**
     * Create a user controller to receive REST signals
     *
     * @param userDAO The Data Access Object
     */
    public UserController(UserDAO userDAO, UserAuthDAO userAuthDAO) {
        this.UserDAO = userDAO;
        this.userAuthDAO = userAuthDAO;
    }

    /**
     * Creates a User with the provided object
     *
     * @return OK response and the user if it was successful, INTERNAL_SERVER_ERROR
     *         otherwise
     */
    @PostMapping("")
    public ResponseEntity<Boolean> createUser(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String password = params.get("password");

        try {
            if (UserDAO.addUser(User.create(username, password)) != null) {
                return new ResponseEntity<>(true, HttpStatus.CREATED);
            } else {
                return new ResponseEntity<>(HttpStatus.CONFLICT);
            }

        } catch (IOException ex) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Responds to the GET request for a {@linkplain User user} for the given id
     * 
     * @return ResponseEntity with {@link User user} object and HTTP status of OK if
     *         found<br>
     *         ResponseEntity with HTTP status of NOT_FOUND if not found<br>
     *         ResponseEntity with HTTP status of INTERNAL_SERVER_ERROR otherwise
     */
    @GetMapping("/{username}")
    public ResponseEntity<User> getUser(@PathVariable String username, @RequestHeader("jelly-api-key") String key) {
        LOG.log(Level.INFO, "GET /user/{0}", username);

        var userAuth = userAuthDAO.getUserAuth(key);
        if (userAuth == null || !userAuth.getUsername().equals(username)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }

        try {
            User user = UserDAO.getUser(username);
            if (user != null) {
                return new ResponseEntity<>(user.withoutPasswordHash(), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

        } catch (IOException e) {
            LOG.log(Level.SEVERE, e.getLocalizedMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * Updates a User with the provided one
     * 
     * @param user The user to update
     * @return OK response and the user if it was successful, or
     *         INTERNAL_SERVER_ERROR if there was an issue
     */
    @PutMapping("/{name}")
    public ResponseEntity<User> updateUser(@RequestBody User user, @PathVariable String name, @RequestHeader("jelly-api-key") String key) {

        var userAuth = userAuthDAO.getUserAuth(key);
        if (userAuth == null || !userAuth.getUsername().equals(user.getUsername())) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }

        try {
            user = UserDAO.updateUser(user, name);
            if (user != null) {
                return new ResponseEntity<>(user, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Deletes a user with the desired name
     * 
     * @param username The name of the user
     * @return OK if the user was deleted, NOT_FOUND if the user was not found, or
     *         INTERNAL_SERVER_ERROR if an error occurred
     */
    @DeleteMapping("/{username}")
    public ResponseEntity<User> deleteUser(@PathVariable String username, @RequestHeader("jelly-api-key") String key) {

        var userAuth = userAuthDAO.getUserAuth(key);
        if (userAuth == null || !userAuth.getUsername().equals(username)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }

        try {
            if (UserDAO.deleteUser(username)) {
                return new ResponseEntity<>(HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}