package test05.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import test05.pojo.Result;
import test05.pojo.Teacher;
import test05.service.TeacherService;

@RestController
@RequestMapping("/teacherAction")
public class TeacherController {
    private final TeacherService teacherService;
    @Autowired
    public TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @RequestMapping("/get")
    public Result get(Teacher teacher, Integer page, Integer pageSize) {
        if (pageSize == null) {
            pageSize = 10;
        }
        if (page == null) {
            page = 1;
        }
        int offset = Math.max(0, (page - 1)) * pageSize;
        return teacherService.getTeacher(teacher, offset, pageSize);
    }

    @RequestMapping("/add")
    public Result add(Teacher teacher) {
        if (teacher == null || teacher.getId() != -1) {
            return Result.error("bad request");
        }else{
            return teacherService.addTeacher(teacher);
        }
    }

    @RequestMapping("/edit")
    public Result edit(Teacher teacher) {
        if (teacher == null || teacher.getId() == -1) {
            return Result.error("bad request");
        }
        return teacherService.updateTeacher(teacher);
    }

    @RequestMapping("/delete")
    public Result delete(Teacher teacher) {
        if (teacher == null || teacher.getId() <= 0) {
            return Result.error("bad request");
        }
        return teacherService.deleteTeacher(teacher);
    }
}
