package com.purui.prims.headless.api.pojo.response;

import com.purui.prims.common.pojo.RecordInfo;
import com.purui.prims.headless.api.pojo.enums.EngineType;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数据库连接属性
 * @author charlie
 * @date   2024/6/25
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(value = "数据源")
public class DatabaseResp extends RecordInfo {

    @ApiModelProperty(value = "数据源ID")
    private Long id;

    @ApiModelProperty(value = "数据源名称")
    private String name;

    @ApiModelProperty(value = "数据源描述")
    private String description;

    @ApiModelProperty(value = "类型")
    private String type;

    @ApiModelProperty(value = "连接地址")
    private String url;

    @ApiModelProperty(value = "用户名")
    private String username;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "数据库")
    private String database;

    @ApiModelProperty(value = "版本")
    private String version;

    @ApiModelProperty(value = "模式")
    private String schema;

    @ApiModelProperty(value = "是否可以使用")
    private boolean hasUsePermission = false;

    @ApiModelProperty(value = "是否可以编辑")
    private boolean hasEditPermission = false;

    public String getHost() {
        Pattern p = Pattern.compile("jdbc:(?<db>\\w+):.*((//)|@)(?<host>.+):(?<port>\\d+).*");
        Matcher m = p.matcher(url);
        if (m.find()) {
            return m.group("host");
        }
        return "";
    }

    public String getPort() {
        Pattern p = Pattern.compile("jdbc:(?<db>\\w+):.*((//)|@)(?<host>.+):(?<port>\\d+).*");
        Matcher m = p.matcher(url);
        if (m.find()) {
            return m.group("port");
        }
        return "";
    }

    /**
     * 是否支持物化视图
     * @return
     */
    public boolean isSupportMaterializedView() {
        return EngineType.DORIS.getName().equalsIgnoreCase(type);
    }

}