package com.adbglobal.parking.crm.controller;

import com.adbglobal.parking.crm.api.UserApi;
import com.adbglobal.parking.crm.exception.UserNotFoundException;
import com.adbglobal.parking.crm.model.Error;
import com.adbglobal.parking.crm.model.User;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class UserController implements UserApi {

    private static final Map<String, User> users = new HashMap<>();

    @Override
    @RequestMapping(method = RequestMethod.POST,
                    consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<User> addUser(@RequestBody final User user) {
        if (!StringUtils.hasText(user.getUserId())) {
            user.setUserId(UUID.randomUUID().toString());
        }
        users.put(user.getUserId(), user);
        return ResponseEntity.ok(user);
    }

    @Override
    @RequestMapping(method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Collection<User>> getUsers() {
        return ResponseEntity.ok(users.values());
    }

    @Override
    @RequestMapping(value = "/{userId}",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<User> getUser(@PathVariable final String userId) {
        final User user = users.get(userId);
        if (user == null) {
            final String message = String.format("User with userId='%s' not found.", userId);
            throw new UserNotFoundException(message);
        }
        return ResponseEntity.ok(users.get(userId));
    }

    @ExceptionHandler({ UserNotFoundException.class })
    public ResponseEntity<Error> handleUserNotFoundException(final UserNotFoundException e) {
        final Error error = new Error();
        error.setMessage(e.getMessage());
        error.setStatus(HttpStatus.NOT_FOUND.value());
        return new ResponseEntity(error, HttpStatus.NOT_FOUND);
    }
}
