package org.matrix.autotest.controller;

import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.matrix.actuators.datasource.IDataSourceService;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


/**
 * SqlController.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2022/1/24 at 8:57 PM
 * Suffering is the most powerful teacher of life.
 */
@RequestMapping("/db")
@RestController
@AllArgsConstructor
public class SqlController {

    private final JdbcTemplate jdbcTemplate;
    private final IDataSourceService dataSourceService;

    @SuppressWarnings("FieldCanBeLocal")
    private final String GET_ALL_TABLES = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='key_stone';";

    /**
     * 运行一段SQL
     *
     * @param sql 要查询的SQL语句
     * @return SQL结果 以MAP的JSON形式传，但是字段数量不固定
     */
    @GetMapping("/sql")
    @ApiOperation("运行一段SQL")
    public ResponseEntity<List<Map<String, Object>>> runSql(@RequestParam String sql) {
        // todo 这里要增加切换数据源的部分
        dataSourceService.switchMainDataSource();
        return ResponseEntity.ok(jdbcTemplate.queryForList(sql));
    }

    /**
     * 获得默认主库的所有表的名称
     *
     * @return 默认主库的所有表的名称
     */
    @GetMapping("/tableNames")
    @ApiOperation("获得默认主库的所有表的名称")
    public ResponseEntity<List<Map<String, Object>>> getTableNames() {
        return ResponseEntity.ok(jdbcTemplate.queryForList(GET_ALL_TABLES));
    }
    
}
