package com.salpa.subject.service.impl;

import com.salpa.common.config.SalpaConfig;
import com.salpa.common.constant.UserConstants;
import com.salpa.subject.domain.MonitorDatabaseType;
import com.salpa.subject.mapper.DatabaseTypeMapper;
import com.salpa.subject.service.DatabaseTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

@Service
public class DatabaseTypeServiceImpl implements DatabaseTypeService {

    @Autowired
    private DatabaseTypeMapper databaseTypeMapper;

    /**
     * 获取数据库类型列表
     * @author zhuff
     * @return
     */
    @Override
    public List<MonitorDatabaseType> getDatabaseTypeAll() {
        return databaseTypeMapper.getDatabaseTypeAll();
    }

    /**
     * 获取数据库类型列表
     * @author zhuff
     * @return
     */
    @Override
    public List<MonitorDatabaseType> getList(String databaseType) {
        List<MonitorDatabaseType> list = databaseTypeMapper.getList(databaseType);
        for (MonitorDatabaseType monitorDatabaseType : list) {
            int count = databaseTypeMapper.countDataSource(monitorDatabaseType.getDatabaseType());
        }
        return list;
    }

    /**
     * 新增数据库类型
     * @param monitorDatabaseType
     * @return
     */
    @Override
    public int addDatabaseType(MonitorDatabaseType monitorDatabaseType) {

        return databaseTypeMapper.addDatabaseType(monitorDatabaseType);
    }

    /**
     * 修改数据库类型
     * @param monitorDatabaseType
     * @return
     */
    @Override
    public int updateDatabaseType(MonitorDatabaseType monitorDatabaseType) {
        return databaseTypeMapper.updateDatabaseType(monitorDatabaseType);
    }

    /**
     * 删除数据库类型
     * @param id
     * @return
     */
    @Override
    public int deleteDatabaseType(Integer id) {
        return databaseTypeMapper.deleteDatabaseType(id);
    }

    /**
     * 根据url解析数据库驱动类名
     * @param jdbcDriverFileUrl
     * @return
     */
    @Override
    public String resolveDriverClassName(String jdbcDriverFileUrl) {
        String className = "";
        /*下载驱动*/
        try {
            URL url = new URL(jdbcDriverFileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 得到输入流
            InputStream inputStream = conn.getInputStream();
            // 获取字节数组
            byte[] getData = readInputStream(inputStream);
            // 获取文件名
            String[] split = jdbcDriverFileUrl.split("/");
            String fileName = split[split.length-1];
            // 文件保存位置
            File saveDir = new File(SalpaConfig.getDriverPath());
            if (!saveDir.exists()) {
                saveDir.mkdir();
            } else {
                saveDir.delete();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            /*获取类名*/
            JarFile jarFile = new JarFile(saveDir + File.separator + fileName);
            ZipEntry entry = jarFile.getEntry("META-INF/services/java.sql.Driver");
            InputStream stream = jarFile.getInputStream(entry);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            className =  reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return className;
    }

    /**
     * 根据path解析数据库驱动类名
     * @param jdbcDriverFilePath
     * @return
     */
    @Override
    public String resolveDriverClassNameFromLocal(String jdbcDriverFilePath) {
        String className = "";
        try {
            /*获取类名*/
            JarFile jarFile = new JarFile(SalpaConfig.getProfile()+jdbcDriverFilePath);
            ZipEntry entry = jarFile.getEntry("META-INF/services/java.sql.Driver");
            InputStream stream = jarFile.getInputStream(entry);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            className =  reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return className;
    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 校验数据库类型是否存在
     * @param databaseType
     * @return
     */
    @Override
    public String checkDatabaseTypeUnique(String databaseType) {
        int count = databaseTypeMapper.checkDatabaseTypeUnique(databaseType);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 根据id获取数据库类型
     * @param id
     * @return
     */
    @Override
    public MonitorDatabaseType getById(Integer id) {
        return databaseTypeMapper.getById(id);
    }
}
