package cn.edu.tju.se.hero.web;

import java.security.Principal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.tju.se.auth.dao.UserRepository;
import cn.edu.tju.se.hero.domain.Hero;
import cn.edu.tju.se.auth.domain.User;
import cn.edu.tju.se.hero.service.HeroService;

import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;

@RestController
@RequestMapping(value = "/api/heroes")

// @PreAuthorize("hasRole('USER')")

public class HeroController {

	@Autowired
	HeroService heroService;
	@Autowired
	UserRepository userRepository;

	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody List<Hero> getAllHeros(Principal user,
			@RequestParam(value="ownerId", required=false) Long ownerId) {
		//return heroService.getByUserId(userRepository.findByUsername(user.getName()).getId());
		if (ownerId!=null){
			return heroService.getByOwnerId(ownerId);
		} else {
			return heroService.getAll();
		}
	}

	@RequestMapping(method = RequestMethod.GET, value = "/{id}")
	@ResponseStatus(HttpStatus.OK)
	public @ResponseBody Hero getHero(@PathVariable Long id) {
		return heroService.get(id);
	}

	@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
	@ResponseStatus(HttpStatus.OK)
	public Hero updateHeroByPut(@RequestBody Hero hero, @PathVariable Long id) {
		hero.setId(id);
		return heroService.update(hero);
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Hero addHero(@RequestBody Hero hero, Principal user) {
		hero.setOwner(userRepository.findByUsername(user.getName()));
		return heroService.add(hero);
	}

	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
	public void removeHero(@PathVariable Long id) {
		heroService.remove(id);
	}

}
