package com.bubbles.server.web;

import com.bubbles.server.domain.User;
import com.bubbles.server.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by LMSH on 2015/5/11.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value="/{userId}", method = RequestMethod.GET)
    public User user(@PathVariable long userId) {
        User user = userRepository.findOne(userId);
        return user;
    }

    @RequestMapping(value="/deviceId/{deviceId}", method = RequestMethod.GET)
    public User userByDeviceId(@PathVariable String deviceId) {
        List<User> userList = userRepository.findByDeviceId(deviceId);
        if (userList.size() != 1) {
            logger.error("ERROR: Get more than one user by deviceId");
            return null;
        }
        return userList.get(0);
    }

    @RequestMapping(value="/{userId}/avatar", method=RequestMethod.PATCH)  // Partially update
    public int uploadAvatar(@PathVariable long userId, @RequestParam("avatar") byte[] avatar)
    {
        if (!userRepository.exists(userId)) {
            return 0;
        }
        return userRepository.setAvatarByDeviceId(getBytes(1), userId);
    }

    // PUT all update

    @RequestMapping(method=RequestMethod.POST) // new and create
    public int saveUser(User user, BindingResult result)
    {
        return 0;
    }

    private static byte[] getBytes(int data)
    {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (data & 0xff);
        bytes[1] = (byte) ((data & 0xff00) >> 8);
        bytes[2] = (byte) ((data & 0xff0000) >> 16);
        bytes[3] = (byte) ((data & 0xff000000) >> 24);
        return bytes;
    }

}

@@ -1644,19 +1644,20 @@
  public 
-int
+long
  saveUse
@@ -1658,16 +1658,40 @@
 aveUser(
+@ModelAttribute(%22user%22) 
 User use
@@ -1725,32 +1725,209 @@
   %7B%0A        
-return 0
+if (result.hasErrors()) %7B%0A            logger.error(%22Binding error%22);%0A            return 0;%0A        %7D%0A        User userSaved = userRepository.save(user);%0A        return userSaved.getId()
 ;%0A    %7D%0A%0A   

add save rest api