package org.matrix.autotest.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.database.entity.Project;
import org.matrix.database.service.IProjectService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mry
 * @since 2022-01-07
 */
@CrossOrigin
@RestController
@RequestMapping("/projects")
@Api(tags = "对项目project的基本操作")
public class ProjectController {

    private final IProjectService projectService;

    public ProjectController(IProjectService projectService) {
        this.projectService = projectService;
    }

    /**
     * 查询所有项目
     *
     * @return 查询到的所有项目, 以及是否查询成功的提示信息
     */
    @ApiOperation(value = "查询所有项目")
    @GetMapping
    public ResponseEntity<CommonResultObj<List<Project>>> findAllProjects() {
        List<Project> results = Optional.ofNullable(projectService.list()).orElse(new ArrayList<>());
        return results.size() != 0
                ? CommonResult.success(results, "查询成功")
                : CommonResult.failed(results, "查询失败或无数据");
    }

    /**
     * 添加项目
     *
     * @param project 项目对象
     * @return 添加的项目, 以及是否添加成功的提示信息
     */
    @ApiOperation(value = "添加项目")
    @PostMapping
    public ResponseEntity<CommonResultObj<Project>> insertProject(@RequestBody Project project) {
        return CommonResult.pred(projectService::save, project
                , "添加成功", "添加失败或已存在同名项目");
    }

    /**
     * 修改项目
     *
     * @param project 项目对象
     * @return 修改后的项目, 以及是否修改成功的提示信息
     */
    @ApiOperation(value = "修改项目")
    @PutMapping
    public ResponseEntity<CommonResultObj<Project>> updateProject(@RequestBody Project project) {
        return CommonResult.pred(projectService::updateById, project
                , "修改成功", "修改失败");
    }

    /**
     * 删除项目
     *
     * @param id 项目id
     * @return 删除的项目id, 以及是否删除成功的提示信息
     */
    @ApiOperation(value = "根据主键id删除项目")
    @DeleteMapping("/{id}")
    public ResponseEntity<CommonResultObj<Long>> deleteProject(@PathVariable Long id) {
        return CommonResult.pred(projectService::removeById, id
                , "删除成功", "删除失败或id不存在");
    }

}
