package org.matrix.autotest.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.autotest.utils.PageTools;
import org.matrix.database.entity.Connect;
import org.matrix.database.service.IConnectService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mry
 * @since 2022-01-07
 */
@CrossOrigin
@RestController
@RequestMapping("/connects")
@Api(tags = "对于数据库connect的基本操作")
public class ConnectController {

    private final IConnectService connectService;

    public ConnectController(IConnectService connectService) {
        this.connectService = connectService;
    }

    /**
     * 分页查询所有数据库信息
     *
     * @param pageSize 每页多少条数据
     * @param pageNum  当前第几页
     * @param name     数据库名称
     * @return 分页查询的结果, 数据库信息
     */
    @ApiOperation(value = "分页查询数据库信息")
    @GetMapping
    public ResponseEntity<CommonResultObj<Page<Connect>>> findPageConnects(
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "1") int pageNum,
            String name) {
        Page<Connect> results = Optional.ofNullable(connectService.page(Page.of(pageNum, pageSize)
                , Wrappers.lambdaQuery(Connect.class)
                        .like(StringUtils.hasLength(name)
                                , Connect::getName, name))).orElse(new Page<>());
        PageTools.pageTool(pageSize, pageNum, results);
        return CommonResult.success(results, "查询成功");
    }

    /**
     * 添加连接池
     *
     * @param connect 连接池对象
     * @return 添加的连接池, 以及是否添加成功的提示信息
     */
    @ApiOperation(value = "添加连接池")
    @PostMapping
    public ResponseEntity<CommonResultObj<Connect>> insertConnect(@RequestBody Connect connect) {
        return CommonResult.pred(connectService::save, connect
                , "添加成功", "添加失败");
    }

    /**
     * 修改连接池
     *
     * @param connect 连接池对象
     * @return 修改后的连接池, 以及是否修改成功的提示信息
     */
    @ApiOperation(value = "修改连接池")
    @PutMapping
    public ResponseEntity<CommonResultObj<Connect>> updateConnect(@RequestBody Connect connect) {
        return CommonResult.pred(connectService::updateById, connect
                , "修改成功", "修改失败");
    }

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

}
