package com.mobvista.apptag.utils;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;

import java.util.HashSet;
import java.util.Set;

/**
 * @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 GetPackageFromMongo {
    public static void main(String[] args) {
        try {
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            //  build the connection options,set the max wait time in (ms)
            builder.maxConnectionIdleTime(300000);
            MongoClientOptions opts = builder.build();

            //  MongoCredential credential2 = MongoCredential.createCredential("username", "databasename",password2);


            //add your option to the connection

            //  MongoClient mongoClient = new MongoClient(new ServerAddress("server ip",27017), Arrays.asList(credential2),opts);
            // 连接到 mongodb 服务
            String mongoUrl = "internal-beijing-adServerMongo-virginia-1390640500.us-east-1.elb.amazonaws.com";
            MongoClient mongoClient = new MongoClient(new ServerAddress(mongoUrl, 27017), opts);

            // 连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("new_adn");
            System.out.println("Connect to database successfully");

            MongoCollection<Document> collection = mongoDatabase.getCollection("campaign");
            MongoCursor<Document> findIterable = collection.find(Filters.eq("advertiserId", 903)).iterator();

            Set<String> set = new HashSet<>();

            while (findIterable.hasNext()) {
                String json = findIterable.next().toJson();
                if (GsonUtil.String2JsonObject(json).has("packageName")) {
                    String packageName = GsonUtil.String2JsonObject(json).get("packageName").getAsString();
                    if (StringUtils.isNotBlank(packageName)) {
                        set.add(packageName);
                    }
                }
            }
            System.out.println("packageNames.size ===>>> " + set.size());
            MySqlUtil mySqlUtil = new MySqlUtil();
            mySqlUtil.insert(set);
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }
}
