package com.keyware.shandan.datasource.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keyware.shandan.common.entity.Result;
import com.keyware.shandan.datasource.entity.DBDriverVo;
import com.keyware.shandan.datasource.entity.DataSourceVo;
import com.keyware.shandan.datasource.enums.ErrorType;
import com.keyware.shandan.datasource.exception.DBDriverException;
import com.keyware.shandan.datasource.service.DBDriverService;
import com.keyware.shandan.datasource.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * DBToolDriverController
 *
 * @author GuoXin
 * @since 2021/7/28
 */
@RestController
@RequestMapping("/business/drivers")
public class DBDriverController {

    @Autowired
    private DBDriverService driverService;

    @Autowired
    private DataSourceService dataSourceService;


    @GetMapping("/{id}")
    public Result<DBDriverVo> get(@PathVariable String id) {

        return Result.of(driverService.getById(id));
    }

    @GetMapping
    public Result<List<DBDriverVo>> list() {

        return Result.of(driverService.list());
    }

    @DeleteMapping("/{id}")
    public Result<Object> del(@PathVariable String id) throws DBDriverException {
        DataSourceVo dataSource = new DataSourceVo();
        dataSource.setDriverId(id);
        int count = dataSourceService.count(new QueryWrapper<>(dataSource));
        if (count > 0) {
            throw new DBDriverException(ErrorType.DRIVER_DONT_DEL);
        }

        return Result.of(driverService.removeById(id));
    }

    @PostMapping("/upload")
    public Result<Object> upload(MultipartFile file) throws DBDriverException {
        return Result.of(driverService.upload(file));
    }
}
