package com.tlongdev.spicio.controller;

import com.tlongdev.spicio.domain.User;
import com.tlongdev.spicio.storage.dao.SequenceDao;
import com.tlongdev.spicio.storage.dao.UserDao;
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.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

/**
 * @author Long
 * @since 2016. 03. 15.
 */
@RestController
@RequestMapping("/api/v1/users")
public class UserController {

    @Autowired private UserDao userDao;
    @Autowired private SequenceDao sequenceDao;

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public User getUser(@PathVariable long userId) {
        User user = userDao.getUser(userId);
        if (user == null) {
            User notFoundUser = new User();
            notFoundUser.setId(userId);
            return notFoundUser;
        }
        return user;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> addUser(@RequestBody User user) {
        if (user.getFacebookId() != null) {
            User result = userDao.getUserByFacebookId(user.getFacebookId());
            if (result == null) {
                user.setId(sequenceDao.nextValue("user"));
                result = userDao.saveUser(user);
            }
            return mapToResponseEntity(result);
        } else if (user.getGoogleId() != null) {
            User result = userDao.getUserByGoogleId(user.getGoogleId());
            if (result == null) {
                user.setId(sequenceDao.nextValue("user"));
                result = userDao.saveUser(user);
            }
            return mapToResponseEntity(result);
        }
        return new ResponseEntity<>(null, null, HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity<?> mapToResponseEntity(User user) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setLocation(ServletUriComponentsBuilder
                .fromCurrentRequest().path("/{id}")
                .buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
    }
}

@@ -798,20 +798,36 @@
  public 
+ResponseEntity%3C
 User
+%3E
  getUser
@@ -945,77 +945,56 @@
     
-User notFoundUser = new User();%0A            notFoundUser.setId(userId
+return new ResponseEntity%3C%3E(HttpStatus.NOT_FOUND
 );%0A 
@@ -998,30 +998,36 @@
 ;%0A      
+  %7D%0A
       
+  
 return n
 otFoundU
@@ -1022,50 +1022,48 @@
 rn n
-otFoundUser;%0A        %7D%0A        return user
+ew ResponseEntity%3C%3E(user, HttpStatus.OK)
 ;%0A  

return responseEntitry