package com.zhenghongfei.todolist.springmvc.controller;

import com.zhenghongfei.todolist.springmvc.model.Todo;
import com.zhenghongfei.todolist.springmvc.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Simple Description
 * <p>
 * Author: Hongfei
 * Date: 2016-12-04
 * Since: 1.0
 */
@Controller
@RequestMapping("/api/todo")
public class TodoController {

    @Autowired
    private TodoService todoService;

    @RequestMapping(method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public List<Todo> findAll() {
        return todoService.findAll();
    }

    @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public Todo create(@RequestBody Todo todo) {
        Assert.notNull(todo);
        return todoService.create(todo);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.OK)
    public void update(@RequestBody Todo todo, @PathVariable int id) {
        Assert.isTrue(todo.getId() == id);
        todoService.update(todo);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.OK)
    public void remove(@PathVariable int id) {
        todoService.remove(id);
    }
}