package com.mobvista.apptag.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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");
            Statement stmt = con.createStatement();
            String insert_sql = "INSERT INTO tag_list(package_name, platform, install) VALUES('@packageName','@platform',10000000000) ON DUPLICATE KEY INGORE tag = tag";
            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", "");
                        }
                    }
                    stmt.executeQuery(insert_sql.replace("@packageName", packageName).replace("@platform", platform));
                }
            }
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
