package com.mobvista.apptag.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @package: com.mobvista.apptag.utils
 * @author: wangjf
 * @date: 2019-07-17
 * @time: 11:38
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class MySqlUtil {
    void insert(Set<String> set) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://dataplatform-app-tag.c5yzcdreb1xr.us-east-1.rds.amazonaws.com:3306/app_tag?useUnicode=true&characterEncoding=utf8&useSSL=false", "apptag_rw", "7gyLEVtkER3u8c9");
            String insertSql = "INSERT INTO tag_list(package_name, platform, install) VALUES @VALUES ON DUPLICATE KEY UPDATE tag = tag";
            StringBuilder stringBuilder = new StringBuilder();
            Iterator<String> iset = set.iterator();
            while (iset.hasNext()) {
                String platform;
                String packageName = iset.next();
                Pattern iosPkgPtn = Pattern.compile("^\\d+$");
                Pattern adrPkgPtn = Pattern.compile("^[0-9a-zA-Z\\.]+$");
                if (iosPkgPtn.matcher(packageName).matches() || adrPkgPtn.matcher(packageName).matches()) {
                    if (packageName.contains(".")) {
                        platform = "Android";
                    } else {
                        platform = "IOS";
                        if (packageName != null && packageName.matches("^id\\d+$")) {
                            packageName = packageName.replace("id", "");
                        }
                    }
                    stringBuilder.append("('").append(packageName).append("','").append(platform).append("',").append("10000000000),");
                }
            }
            PreparedStatement stmt = con.prepareStatement(insertSql.replace("@VALUES", stringBuilder.substring(0, stringBuilder.length() - 1)));
            stmt.execute();
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
