package com.cm.common.plugin.service.database.impl;

import com.cm.common.base.AbstractService;
import com.cm.common.exception.RemoveException;
import com.cm.common.exception.SaveException;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.service.database.IDatabaseService;
import com.cm.common.result.SuccessResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @ClassName: DatabaseServiceImpl
 * @Description: 数据库
 * @Author: WangGeng
 * @Date: 2019-07-14 18:20
 * @Version: 1.0
 **/
@Service
public class DatabaseServiceImpl extends AbstractService implements IDatabaseService {

    @Override
    public SuccessResult saveConnection(Map<String, Object> params) throws SaveException, RemoveException, SearchException {
        openConnection(params);
        return new SuccessResult();
    }

    @Override
    public void openConnection(Map<String, Object> params) throws SaveException, RemoveException, SearchException {
        LOG.debug("关闭原有链接");
        closeConnection(getConnectionFromSession());
        LOG.debug("创建新连接");
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName(getDriverClass(params.get("dialect").toString()));
        String url = null;
        if (StringUtils.equals(DATABASE_MYSQL, params.get("dialect").toString())) {
            url = String.format("jdbc:%s://%s:%s/%s?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false", params.get("dialect").toString(), params.get("ip").toString(), params.get("port").toString(), params.get("dbName"));
        }
        driverManagerDataSource.setUrl(url);
        driverManagerDataSource.setUsername(params.get("username").toString());
        driverManagerDataSource.setPassword(params.get("password").toString());
        try {
            Connection connection = driverManagerDataSource.getConnection();
            HttpSession session = getHttpSession();
            session.setAttribute(DATABASE_CONNECTION, connection);
            session.setAttribute(DATABASE_NAME, params.get("dbName").toString());
        } catch (SQLException e) {
            LOG.error(e.getMessage(), e);
            throw new SaveException("打开数据库连接失败");
        }
    }

    @Override
    public SuccessResult removeConnection(Map<String, Object> params) throws RemoveException, SearchException {
        closeConnection(getConnectionFromSession());
        HttpSession session = getHttpSession();
        session.removeAttribute(DATABASE_CONNECTION);
        session.removeAttribute(DATABASE_NAME);
        return new SuccessResult();
    }

    /**
     * 从session中获取connection
     *
     * @return
     */
    private Connection getConnectionFromSession() {
        return (Connection) getHttpSession().getAttribute(DATABASE_CONNECTION);
    }

    /**
     * 关闭connection
     *
     * @param connection
     * @throws RemoveException
     */
    private void closeConnection(Connection connection) throws RemoveException {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOG.error(e.getMessage(), e);
                throw new RemoveException("删除数据库连接失败");
            }
        }
    }

    /**
     * 获取数据库驱动
     *
     * @param dialect
     * @return
     */
    private String getDriverClass(String dialect) {
        String driverClass;
        switch (dialect) {
            default:
                driverClass = DATABASE_MYSQL_DRIVER_CLASS;
        }
        return driverClass;
    }

}
