package org.matrix.autotest.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.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("/connects")
@Api(tags = "对于数据库connect的基本操作")
public class ConnectController {

    private final IConnectService connectService;

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

//    @ApiOperation(value = "分页查询")
//    @PostMapping("/page")
//    public ResponseEntity<CommonResultObj<PageResult>> findAllPage(@RequestBody PageResult pageResult) {
//        pageResult = connectService.pageAll(pageResult);
//        if (pageResult.getRows() != null) {
//            return CommonResult.success(pageResult, "查询成功");
//        } else {
//            return CommonResult.failed("查询失败或无数据");
//        }
//    }

    /**
     * 查询所有数据库
     *
     * @return 查询到的所有数据库
     */
    @ApiOperation(value = "查询所有")
    @GetMapping
    public ResponseEntity<CommonResultObj<List<Connect>>> findAllConnects() {
        List<Connect> results = Optional.ofNullable(connectService.list()).orElse(new ArrayList<>());
        return results.size() != 0
                ? CommonResult.success(results, "查询成功")
                : CommonResult.failed(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
                , "修改成功", "修改失败");
    }

    /**
     * 删除连接池
     *
     * @param id 连接池id
     * @return 是否删除成功
     */
    @ApiOperation(value = "根据id删除连接池")
    @DeleteMapping("/{id}")
    public ResponseEntity<CommonResultObj<Integer>> deleteConnect(@PathVariable Integer id) {
        return CommonResult.pred(connectService::removeById, id
                , "删除成功", "删除失败");
    }

}

