package com.bocloud.ims.service.resource.azure.db;

import com.bocloud.common.model.BocloudResult;
import com.bocloud.ims.entity.resource.azure.db.AzureDatabaseServer;
import com.bocloud.ims.interfaces.resource.azure.db.DbConnectService;
import com.bocloud.ims.repository.resource.azure.db.CloudDatabaseServerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @Company: 博云 www.bocloud.com
 * @ClassName: DbConnectServiceImpl
 * @Description:
 * @author: zhenpingLi/李振平
 * @date: 2021/2/20 14:00
 */


@Service("dbConnectService")
public class DbConnectServiceImpl implements DbConnectService {

    private static Logger logger = LoggerFactory.getLogger(DbConnectServiceImpl.class);
    @Autowired
    private CloudDatabaseServerRepository cloudDatabaseServerRepository;

    @Override
    public BocloudResult<Map<String, String>> connects(Long id) {
        try {
            AzureDatabaseServer entity = cloudDatabaseServerRepository.query(id);
            if (ObjectUtils.isEmpty(entity)) {
                return new BocloudResult<>(false, "数据库不存在");
            }
            Map<String, String> map = new HashMap<>();
            String adoNet = new StringBuffer()
                    .append("Server=")
                    .append(entity.getFullyQualifiedDomain())
                    .append("; ")
                    .append("Port=3306; ")
                    .append("Database={your_database}; ")
                    .append("Uid=")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append("; ")
                    .append("Pwd={your_password}; ")
                    .append("SslMode=Preferred; ").toString();
            map.put("ADO.NET", adoNet);

            String jdbc = new StringBuffer()
                    .append("String url =\"jdbc:mysql://")
                    .append(entity.getFullyQualifiedDomain())
                    .append(";3306/{your_database}?")
                    .append("useSSL=")
                    .append("Enabled".equalsIgnoreCase(entity.getSslEnforcement()) ? "true" : "false")
                    .append("&requireSSL=false\"; ")
                    .append("myDbConn = DriverManager.getConnection(url,")
                    .append("\"")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append("\"")
                    .append("{your_password});")
                    .toString();
            map.put("JDBC", jdbc);

            String nodeJs = new StringBuffer()
                    .append("var conn = mysql.createConnection({host: ")
                    .append("\"")
                    .append(entity.getFullyQualifiedDomain())
                    .append("\",")
                    .append("user: ")
                    .append("\"")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append("\",")
                    .append("password: {your_password}, database: {your_database}, port: 3306,")
                    .append("ssl:{ca:fs.readFileSync({ca-cert filename})}});")
                    .toString();
            map.put("Node.js", nodeJs);

            String php = new StringBuffer()
                    .append("$con=mysqli_init(); mysqli_ssl_set($con, NULL, NULL, {ca-cert filename}, NULL, NULL);")
                    .append(" mysqli_real_connect($con, ")
                    .append("\"")
                    .append(entity.getFullyQualifiedDomain())
                    .append("\",")
                    .append("user: ")
                    .append("\"")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append("\",")
                    .append("{your_password}, {your_database}, 3306);")
                    .toString();
            map.put("PHP", php);

            String python = new StringBuffer()
                    .append("cnx = mysql.connector.connect(")
                    .append("user=")
                    .append("\"")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append("\",")
                    .append("password={your_password}, ")
                    .append("host=")
                    .append("\"")
                    .append(entity.getFullyQualifiedDomain())
                    .append("\",")
                    .append("port=3306, database={your_database}, ssl_ca={ca-cert filename},")
                    .append("ssl_verify_cert=")
                    .append("Enabled".equalsIgnoreCase(entity.getSslEnforcement()) ? "true" : "false")
                    .append(")")
                    .toString();
            map.put("Python", python);

            String ruby = new StringBuffer()
                    .append("client = Mysql2::Client.new(")
                    .append("username: ")
                    .append("\"")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append("\",")
                    .append("password={your_password}, database: {your_database}, ")
                    .append("host:")
                    .append("\"")
                    .append(entity.getFullyQualifiedDomain())
                    .append("\",")
                    .append("port: 3306, sslca:{ca-cert filename}, ")
                    .append("sslverify:false, ")
                    .append("sslcipher:'AES256-SHA')")
                    .toString();
            map.put("Ruby", ruby);

            String web = new StringBuffer()
                    .append("Database={your_database}; Data Source=")
                    .append(entity.getFullyQualifiedDomain())
                    .append(";")
                    .append("User Id=")
                    .append(entity.getAdministratorName())
                    .append("@")
                    .append(entity.getName())
                    .append(";")
                    .append("Password={your_password}")
                    .toString();
            map.put("Web 应用", web);

            return new BocloudResult<>(true, map, "查询成功");
        } catch (Exception e) {
            logger.error("query connectString error!", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }
}