package cn.reghao.tnb.sb.db.mongo;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.tnb.sb.db.mongo.model.UserComment;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.*;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author reghao
 * @date 2024-12-08 14:32:04
 */
//@Component
public class MongoClientUtil {
    private final JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();

    public void mongo() {
        String host = "127.0.0.1";
        String authDB = "admin";
        String username = "dev";
        String password = "Dev@123456";

        ServerAddress serverAddress = new ServerAddress(host);
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyToSocketSettings(builder ->
                        builder.readTimeout(0, TimeUnit.SECONDS)
                                .connectTimeout(0, TimeUnit.SECONDS))
                .applyToConnectionPoolSettings(builder ->
                        builder.minSize(10).maxSize(20)
                                .maxConnectionIdleTime(0, TimeUnit.SECONDS)
                                .maxConnectionLifeTime(0, TimeUnit.SECONDS))
                .credential(MongoCredential.createCredential(username, authDB, password.toCharArray()))
                .applyToServerSettings(builder ->
                        builder.minHeartbeatFrequency(10, TimeUnit.SECONDS)
                                .heartbeatFrequency(20, TimeUnit.SECONDS))
                .applyToClusterSettings(builder -> builder.hosts(List.of(serverAddress)))
                .build();

        MongoClient mongoClient = MongoClients.create(mongoClientSettings);
        JsonWriterSettings settings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();

        MongoDatabase db = mongoClient.getDatabase("tnb_content_tdb");
        MongoCollection<Document> videoCol = db.getCollection("UserComment");

        BasicDBObject query = new BasicDBObject();
        String videoId = "123456";
        query.put("commentId", videoId);

        Document document = videoCol.find(query).first();
        if (document == null) {
            return;
        }

        document.remove("createTime");
        document.remove("updateTime");

        String jsonData = document.toJson(settings);
        UserComment userComment = JsonConverter.jsonToObject(jsonData, UserComment.class);
    }

    private MongoDatabase getMongoDatabase(String dbName) {
        String host = "127.0.0.1";
        String authDB = "admin";
        String username = "dev";
        String password = "Dev@123456";

        ServerAddress serverAddress = new ServerAddress(host);
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyToSocketSettings(builder ->
                        builder.readTimeout(0, TimeUnit.SECONDS)
                                .connectTimeout(0, TimeUnit.SECONDS))
                .applyToConnectionPoolSettings(builder ->
                        builder.minSize(10).maxSize(20)
                                .maxConnectionIdleTime(0, TimeUnit.SECONDS)
                                .maxConnectionLifeTime(0, TimeUnit.SECONDS))
                .credential(MongoCredential.createCredential(username, authDB, password.toCharArray()))
                //.applicationName("SpiderParser")
                .applyToServerSettings(builder ->
                        builder.minHeartbeatFrequency(10, TimeUnit.SECONDS)
                                .heartbeatFrequency(20, TimeUnit.SECONDS))
                .applyToClusterSettings(builder -> builder.hosts(List.of(serverAddress)))
                .build();

        MongoClient mongoClient = MongoClients.create(mongoClientSettings);
        return mongoClient.getDatabase(dbName);
    }

    public MongoCollection<Document> getCollection(String colName) {
        String host = "127.0.0.1";
        String authDB = "admin";
        String username = "dev";
        String password = "Dev@123456";

        ServerAddress serverAddress = new ServerAddress(host);
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyToSocketSettings(builder ->
                        builder.readTimeout(0, TimeUnit.SECONDS)
                                .connectTimeout(0, TimeUnit.SECONDS))
                .applyToConnectionPoolSettings(builder ->
                        builder.minSize(10).maxSize(20)
                                .maxConnectionIdleTime(0, TimeUnit.SECONDS)
                                .maxConnectionLifeTime(0, TimeUnit.SECONDS))
                .credential(MongoCredential.createCredential(username, authDB, password.toCharArray()))
                //.applicationName("SpiderParser")
                .applyToServerSettings(builder ->
                        builder.minHeartbeatFrequency(10, TimeUnit.SECONDS)
                                .heartbeatFrequency(20, TimeUnit.SECONDS))
                .applyToClusterSettings(builder -> builder.hosts(List.of(serverAddress)))
                .build();

        MongoClient mongoClient = MongoClients.create(mongoClientSettings);
        MongoDatabase db = mongoClient.getDatabase("tnb_content_tdb");
        return db.getCollection(colName);
    }

    public UserComment getVideoUser(String videoId, MongoCollection<Document> videoCol) {
        BasicDBObject query = new BasicDBObject();
        query.put("bvId", videoId);
        query.put("feedVideo", false);

        Document document = videoCol.find(query).first();
        if (document == null) {
            return null;
        }

        Object object = document.get("biliUser");
        if (object instanceof Document) {
            Document user = (Document) object;
            user.remove("createTime");
            user.remove("updateTime");

            String jsonData = user.toJson(settings);
            return JsonConverter.jsonToObject(jsonData, UserComment.class);
        }

        return null;
    }

    public void updateVideo(String videoId, MongoCollection<Document> videoCol) {
        BasicDBObject filter = new BasicDBObject();
        filter.put("bvId", videoId);
        Bson update = new Document("$set", new Document().append("feedVideo", true));
        videoCol.updateOne(filter, update);
    }

    private void findAll(BasicDBObject query, MongoCollection<Document> videoCol) {
        //MongoCursor<Document> cursor = videoCol.find(query).sort(Sorts.orderBy(Sorts.descending("times"))).skip(0).limit(10).iterator();
        MongoCursor<Document> cursor = videoCol.find(query).skip(0).limit(1).iterator();
        if (cursor.hasNext()) {
            Document document1 = cursor.next();
            System.out.println();
        }
    }
}
