package com.libreecm.opencmis.controllers;

import org.apache.chemistry.opencmis.commons.server.CallContext;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;

import com.libreecm.commonAPI.auxiliars.exceptions.AddUserOkException;
import com.libreecm.commonAPI.auxiliars.exceptions.AlreadyExistingUserException;
import com.libreecm.commonAPI.configuration.ComponentConfig;
import com.libreecm.commonAPI.model.users.LibreECMUser;
import com.libreecm.opencmis.consumers.UserConsumer;

public class UserController extends BaseController {
    @Autowired
    CallContext context;
    
    /**
     * Function that returns the current user from client
     * @return
     */
    @RequestMapping(value = "/currentuser", method = RequestMethod.GET)
    @ResponseBody
    public String getCurrentUserId() {
    	UserConsumer consumer = new UserConsumer();
    	String userName = context.getUsername();
    	return consumer.getUserByName(userName, ComponentConfig.getConfig().getMainCurrentUserUrl()).getId();
    }
    
    /**
     * A class that saves a User to the DDBB
     * @param user
     * @return
     * @throws AlreadyExistingUserException 
     * @throws AddUserOkException 
     */
    @RequestMapping(value="/user", method = RequestMethod.POST)
    public @ResponseBody LibreECMUser saveUser(@RequestBody LibreECMUser user) throws AlreadyExistingUserException, AddUserOkException {
    	//validateUser();
    	UserConsumer consumer = new UserConsumer();
    	return consumer.setUser(user, ComponentConfig.getConfig().getMainUserUrl());
    }
    
    /**
     * A class that gets a User from the DDBB
     * @param id String id
     * @return 
     */
    @RequestMapping(value="/user", method = RequestMethod.GET)
    public @ResponseBody LibreECMUser getUser(@RequestBody String id) {
    	//validateUser();
    	UserConsumer consumer = new UserConsumer();
    	return consumer.getUser(id, ComponentConfig.getConfig().getMainUserUrl());
    }
}
