package cn.ibizlab.core.data.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.util.Set;


@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DSLink
{

        private String name;
        private String description;
        private String type;
        private String driverClassName;
        private String url;
        private String username;
        private String password;
        private String schema;
        private Set<String> usings;

        @JSONField(serialize = false)
        @JsonIgnore
        public boolean isMongodb()
        {
                return "mongodb".equalsIgnoreCase(this.getType())||(this.getUrl()!=null&&this.getUrl().startsWith("mongodb"));
        }

        @JSONField(serialize = false)
        @JsonIgnore
        public boolean isDatabase()
        {
                return (!StringUtils.isEmpty(this.getDriverClassName()))&&(!StringUtils.isEmpty(this.getUrl()));
        }

        @JSONField(serialize = false)
        @JsonIgnore
        public boolean isElasticSearch()
        {
                return "elasticsearch".equalsIgnoreCase(this.getType())||"es".equalsIgnoreCase(this.getType());
        }

        @JSONField(serialize = false)
        @JsonIgnore
        public boolean isCassandra()
        {
                return "cassandra".equalsIgnoreCase(this.getType());
        }

        @JSONField(serialize = false)
        @JsonIgnore
        public DSLink push()
        {
                if(this.isDatabase()&&(!StringUtils.isEmpty(name)))
                        DynamicDataSourceContextHolder.push(name);
                return this;
        }

        private static DSLink defaultLink;
        public static DSLink getDefaultLink()
        {
                if(defaultLink==null)
                        defaultLink=new DSLink().setName("master").setType("mysql");
                return defaultLink;
        }
}
