package test05.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import test05.mapper.CourseMapper;
import test05.pojo.Course;
import test05.pojo.Result;
import test05.service.CourseService;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {


    private final CourseMapper courseMapper;

    private String courseCheck(Course course) {
        if (course.getId()!=-1){
            return "do not set N_COURSE_ID";
        }
        if (course.getName().length()<4||course.getName().length()>25){
            return "name invalid";
        }
        if (course.getGrade()>3000||course.getGrade()<2000){
            return "grade invalid";
        }
        if (course.getMajor()<1||course.getMajor()>6){
            return "major invalid";
        }
        if (course.getType()<1||course.getType()>6){
            return "type invalid";
        }
        if (course.getDetail().length()>200){
            return "detail too long";
        }
        return "ok";
    }

    @Autowired
    public CourseServiceImpl(CourseMapper courseMapper) {
        this.courseMapper = courseMapper;
    }

    @Override
    public Result addCourse(Course course) {
        String check = courseCheck(course);
        if (!check.equals("ok")){
            return Result.error(check);
        }
        if (courseMapper.insertCourse(course) > 0 && course.getId()!=-1){
            return Result.success(course);
        }else{
            return Result.error("add course error");
        }
    }

    @Override
    public Result deleteCourse(Course course) {
        if (courseMapper.deleteCourse(course)>=1){
            return Result.success(course);
        }else{
            return Result.error("delete course error");
        }
    }

    @Override
    public Result updateCourse(Course course) {
        String check = courseCheck(course);
        if (!course.isComplete()&&check.equals("ok")){
            return Result.error("please complete the course:"+check);
        }else if(courseMapper.updateCourse(course)>=1){
            return Result.success(course);
        }else{
            return Result.error("update course error");
        }
    }

    @Override
    public Result getCourse(Course course, int page, int pageSize) {
        int offset = Math.max(0, (page - 1)) * pageSize;
        List<Course> courseList = courseMapper.selectCourse(course, offset, pageSize);
        int total = courseMapper.selectCourseCount(course);
        return Result.success(courseList, total);
    }
}
