import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.commons.lang3.RandomStringUtils;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class UsersGenerator {

    private static final String MONGO_DB_URL = "mongodb://192.168.52.128:27033/";
    private static final String DB_NAME = "MoviesDB";
    private static final String COLLECTION_NAME = "users";

    private static final Random random = new Random();

    private static final String[] MOVIE_POOL = {"Inside out", "Aladdin", "Avatar", "Inception", "Interstellar", "Matrix", "Up", "Soul"};

    public static void main(String[] args) {
        try (MongoClient mongoClient = MongoClients.create(MONGO_DB_URL)) {
            MongoDatabase database = mongoClient.getDatabase(DB_NAME);
            generateUsers(5000, database, COLLECTION_NAME);
        }
    }

    private static void generateUsers(int numberOfUsers, MongoDatabase database, String collectionName) {
        MongoCollection<Document> collection = database.getCollection(collectionName);

        collection.deleteMany(new Document());

        List<Document> documents = new ArrayList<>();
        System.out.println("Generating " + numberOfUsers + " users...");

        for (int i = 0; i < numberOfUsers; i++) {
            Document user = new Document();
            user.append("user_name", generateRandomName())
                    .append("watched_movies", generateWatchedMovies())
                    .append("subscription_month", random.nextInt(12) + 1);

            documents.add(user);

            if (documents.size() == 1000) {
                collection.insertMany(documents);
                documents.clear();
            }
        }
        if (!documents.isEmpty()) collection.insertMany(documents);
        System.out.println("Finished generating users successfully!");
    }

    private static String generateRandomName() {
        return RandomStringUtils.randomAlphabetic(5, 8);
    }

    private static List<String> generateWatchedMovies() {
        int count = random.nextInt(3) + 1;
        List<String> watched = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            watched.add(MOVIE_POOL[random.nextInt(MOVIE_POOL.length)]);
        }
        return watched;
    }
}