package com.mobvista.apptag.main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.HashSet;
import java.util.Set;

/**
 * @package: com.mobvista.apptag.main
 * @author: wangjf
 * @date: 2020/3/17
 * @time: 11:52 上午
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class JoypacMain {
    public static final Logger logger = LoggerFactory.getLogger(JoypacMain.class);

    public static void main(String[] args) {
        insertDmp(readJoypac());
    }

    static void insertDmp(Set<String> set) {
        final String CONNECTION_URL = "jdbc:mysql://dataplatform-app-tag.c5yzcdreb1xr.us-east-1.rds.amazonaws.com:3306/dmp?useUnicode=true&characterEncoding=utf8&useSSL=false";
        final String DRIVER = "com.mysql.jdbc.Driver";
        final String USER = "apptag_rw";
        final String PASSWORD = "7gyLEVtkER3u8c9";
        try {
            Class.forName(DRIVER);
            Connection con = DriverManager.getConnection(CONNECTION_URL, USER, PASSWORD);
            String insertSql = "REPLACE INTO package_list(package_name) VALUES @VALUES";
            StringBuilder stringBuilder = new StringBuilder();
            for (String packageName : set) {
                stringBuilder.append("('").append(packageName).append("'),");
            }
            PreparedStatement stmt = con.prepareStatement(insertSql.replace("@VALUES", stringBuilder.substring(0, stringBuilder.length() - 1)));
            logger.info("INSERT " + set.size() + " package_names!!!");
            stmt.execute();
            con.close();
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    static Set<String> readJoypac() {
        final String CONNECTION_URL = "jdbc:mysql://rm-j6c26ox9wdgghld77fo.mysql.rds.aliyuncs.com:3306/jp_base?useUnicode=true&characterEncoding=utf8&useSSL=false";
        final String DRIVER = "com.mysql.jdbc.Driver";
        final String USER = "jpbase_fordmp";
        final String PASSWORD = "3Pi6bWj9cja3vjs";
        Set<String> set = new HashSet<>();
        try {
            Class.forName(DRIVER);
            Connection con = DriverManager.getConnection(CONNECTION_URL, USER, PASSWORD);
            String sql = "SELECT DISTINCT package FROM app";
            PreparedStatement preparedStatement = con.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                set.add(resultSet.getString("package"));
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return set;
    }
}
