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

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;

import cn.edu.tju.se.base.domain.Address;
import cn.edu.tju.se.base.exception.MyException;
import cn.edu.tju.se.base.service.AddressService;

@RestController
@RequestMapping(value = "/addresses")
public class AddressController {

	@Autowired
	AddressService addressService;

	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody List<Address> getAll() {
		return addressService.getAll();
	}

	@RequestMapping(method = RequestMethod.GET, value = "/{id}")
	public @ResponseBody Address getAddress(@PathVariable Long id) {
		Address address1 = addressService.get(id);
		if (address1 == null) {
			throw new MyException(0L);
		}
		return address1;
	}

	@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
	@ResponseStatus(HttpStatus.CREATED)
	public Address updateAddressByPut(@RequestBody Address address,
			@PathVariable Long id) {
		return addressService.update(address);
	}

	@RequestMapping(method = RequestMethod.POST, value = "/{id}")
	@ResponseStatus(HttpStatus.CREATED)
	public Address updateAddressByPost(@RequestBody Address address,
			@PathVariable Long id) {
		return addressService.update(address);
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.CREATED)
	public Address addAddress(@RequestBody Address address) {
		address.setId(null);
		return addressService.add(address);

	}

	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public @ResponseBody void removeAddress(@PathVariable Long id) {
		addressService.remove(id);
	}

}
