package cbd;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.IndexOptions;
import org.bson.Document;
import java.util.concurrent.TimeUnit;
import java.time.Duration;
import java.time.Instant;
import java.util.*;

public class atendimentoA {

    private MongoDatabase db;
    private MongoCollection<Document> col;
    private String username;
    private static int limit = 5; //products limit
    private static long timeslot = 2 * 15 ; //time limit (s)


    public atendimentoA(String username) {

        this.username = username;

        String uri = "mongodb://127.0.0.1:27017";

        MongoClient mongoClient = MongoClients.create(uri);
        MongoDatabase db = mongoClient.getDatabase("cbd");
        this.db = db;
    }	


    public void insertProducts(String prod) {

        if (db.listCollections().filter(Filters.eq("name", "atendimentoA" + this.username)).first() == null) {

            MongoCollection<Document> col = db.getCollection("atendimentoA" + this.username);
            this.col = col;
            col.insertOne(new Document("product", prod)
                        .append("createdAt", new Date()));
            
                      
            col.createIndex(new Document("createdAt", 1), 
                            new IndexOptions().expireAfter(timeslot, TimeUnit.SECONDS));


                            
            col.createIndex(new Document("product", 1));

            System.out.println("Product " + prod + " is now registered");
        }

 

        else {
            long count = col.countDocuments();;

            if (col.find(Filters.eq("product", prod)).first() != null) {
                System.out.println("Product already registered");
                return;
            }  

            if (count == limit){
                System.out.println("Product limit reached for the time interval");

                Document firstProduct = col.find(Filters.exists("createdAt")).first();

                if (firstProduct != null && firstProduct.containsKey("createdAt")) {
                    Date createdAtDate = firstProduct.getDate("createdAt");
                    Instant createdAt = createdAtDate.toInstant();
                    Instant now = Instant.now();

                    long elapsedTime = Duration.between(createdAt, now).getSeconds();

            
                    long remainingTTL = timeslot - elapsedTime;

                    if (remainingTTL > 0) {
                        System.out.println("Please wait " + remainingTTL + " seconds to add different products, or press 'Enter' to quit");
                    } else {
                        //TTL expired, drop the collection and insert the new product
                        col.drop();
                        col = db.getCollection("atendimentoA" + this.username);
                        col.insertOne(new Document("product", prod).append("createdAt", new Date()));
                        System.out.println("Product " + prod + " is now registered");
                        return;
                    }
                }
            return;
        } else {
            // Insert the product without the createdAt timestamp
            col.insertOne(new Document("product", prod));
            System.out.println("Product " + prod + " is now registered");
            return;
        }
    }
}


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Please write your username in order to register products: ");
        String username = scanner.nextLine();
        atendimentoA atendimento = new atendimentoA(username);

        System.out.print("Please write the products you would like to register (press 'Enter' to quit): ");
        String prod = scanner.nextLine();

        while (!prod.isEmpty()) {
            atendimento.insertProducts(prod);
            prod = scanner.nextLine();
        }

        System.out.println("Exiting...");

        scanner.close();    
       
        }
}

