package cbd.redis;

import java.util.Scanner;
import redis.clients.jedis.Jedis;



public class A_Atendimento {

    private Jedis jedis;
    private static int limit = 20; //products limit
    private static int timeslot = 5 * 60 ; //time limit (s)
    

    public A_Atendimento() {
        this.jedis = new Jedis();
    } 

    public void insertProducts(String username, String prod) {

        String key = "atendimentosA:" + username;

        if (!jedis.exists(key)) {
            jedis.sadd(key, prod);
            jedis.expire(key, timeslot);
            System.out.println("Product " + prod + " is now registered");
        }
        else {
            long numProd = jedis.scard(key);

            if (jedis.sismember(key, prod)) {
                System.out.println("Product already registered");
                return;
            }  

            if (numProd == limit){
                System.out.println("Product limit reached for the time interval");
                System.out.println("Please wait " + (jedis.ttl(key)) + " seconds to add different products, or press 'Enter' to quit");
                return;
            }
            else {
                jedis.sadd(key, prod);
                System.out.println("Product " + prod + " is now registered");
                return;
            }  
        }
        return;
    }   
        
        
   


    public static void main(String[] args) {
        A_Atendimento a = new A_Atendimento();
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please write your username in order to register products: ");
        String username = scanner.nextLine();
        System.out.print("Please write the products you would like to register (press 'Enter' to quit): ");
        String prod = scanner.nextLine();

        while (!prod.isEmpty()) {
            a.insertProducts(username, prod);
            prod = scanner.nextLine();
        }

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

        scanner.close();    
        a.jedis.close();	
        
    }
}




